父子进程之间的通信

6 投票
2 回答
10251 浏览
提问于 2025-04-16 18:11

我正在尝试创建一个Python 3程序,这个程序会有一个或多个子进程。

父进程会启动这些子进程,然后继续做自己的事情。偶尔我想给某个特定的子进程发送一条消息,让它接收并采取相应的行动。

此外,子进程在等待消息时需要保持非锁定状态,它会运行自己的循环,维护与服务器的连接,并将收到的任何消息发送回父进程。

目前我在研究Python中的multiprocessing、threading和subprocess模块,但还没有找到解决方案。

我想实现的是程序的主要部分与用户互动,处理用户输入并向用户展示信息。这部分会与子进程异步进行,子进程会与不同的服务器通信,接收来自服务器的消息,并将用户的正确消息发送到服务器。然后,子进程会将信息发送回主程序部分,主程序再将这些信息展示给用户。

我的问题是:

  1. 我这样做是不是错了?
  2. 哪个模块最适合使用?
    2.1 我该如何设置这个?

2 个回答

3

听起来你可能对多进程有些了解,只是对Python不太熟悉。

os.pipe可以给你提供管道,用来连接父进程和子进程。而信号量可以用来协调或传递信息给父进程和子进程之间。你可能还想考虑一下队列,它可以用来发送消息。

7

可以看看Doug Hellmann的(multiprocessing) “进程之间的通信”。这是他每周分享的Python模块系列的一部分。用字典或列表来和一个进程进行交流其实是相当简单的。

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()

撰写回答