父子进程之间的通信

6

我正在尝试创建一个Python 3程序,其中包含一个或多个子进程。

父进程生成子进程,然后继续自己的业务,现在和以后我想发送消息到特定的子进程,该进程接收并采取行动。

此外,子进程需要在等待消息时不被锁定,它将运行自己的循环来维护服务器连接,并将接收到的任何消息发送给父进程。

我目前正在查看Python中的multiprocessing、threading、subprocess模块,但没有找到任何解决方案。

我想要实现的是程序的主要部分与用户交互,处理用户输入并向用户呈现信息,这将异步于与不同服务器通信的子部分,从服务器接收消息并将正确的消息从用户发送到服务器。然后,子进程将向主要部分发送信息,其中它们将呈现给用户。

我的问题是:

  1. 我是否走错了路?
  2. 哪个模块最好使用
    2.1 如何设置

为什么不基于众所周知的IPC机制实现一些东西呢?通过共享内存或套接字(TCP/IP或Unix域套接字)进行通信已经有深入的文档资料。 - user2665694
2个回答

6
参见Doug Hellmann的(multiprocessing) "进程间通信"。这是他Python Module of the Week系列的一部分。使用字典或列表与进程通信相当简单。
import time
from multiprocessing import Process, Manager

def test_f(test_d):
   """  frist process to run
        exit this process when dictionary's 'QUIT' == True
   """
   test_d['2'] = 2     ## change to test this
   while not test_d["QUIT"]:
      print "test_f", test_d["QUIT"]
      test_d["ctr"] += 1
      time.sleep(1.0)

def test_f2(name):
    """ second process to run.  Runs until the for loop exits
    """
    for j in range(0, 10):
       print name, j
       time.sleep(0.5)

    print "second process finished"

if __name__ == '__main__':
    ##--- create a dictionary via Manager
    manager = Manager()
    test_d = manager.dict()
    test_d["ctr"] = 0
    test_d["QUIT"] = False

    ##---  start first process and send dictionary
    p = Process(target=test_f, args=(test_d,))
    p.start()

    ##--- start second process
    p2 = Process(target=test_f2, args=('P2',))
    p2.start()

    ##--- sleep 3 seconds and then change dictionary
    ##     to exit first process
    time.sleep(3.0)
    print "\n terminate first process"
    test_d["QUIT"] = True
    print "test_d changed"
    print "data from first process", test_d

    time.sleep(5.0)
    p.terminate()
    p2.terminate()

谢谢大家的意见,目前工作问题让我将这个爱好项目搁置了几天,但我会查看所有的建议并看看它们是否有帮助。 - Svavelsyra
点赞Doug Hellmann的(多进程)“进程间通信”链接! - ZF007

3
听起来你可能对多进程很熟悉,只是不熟悉 Python。 os.pipe 可以提供连接父进程和子进程的管道。semaphores 可以用于协调/信号父子进程之间的通信。你可能需要考虑使用 queues 传递消息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接