python - 使用python多处理,子进程如何终止另一个子进程?

标签 python

我的主应用程序进程创建了两个子进程。

A = Process(target=a, args=(aaa,))

B = Process(target=b,args=())

为了便于讨论,将它们称为 A 和 B;进程A如何终止进程B?

最佳答案

虽然我真的不建议子进程能够互相攻击。就我个人而言,我会让主进程管理子进程。

如果您想沿着当前所在的路线走下去。您可以执行您想要的操作的一种方法是让主进程将子 A 的进程 id 传递给子 B (或者您想要如何执行此操作) 。使用传递给进程的进程 ID,您可以终止该进程。

选项 1: 如果只有一个进程可以终止另一个进程,那么最简单的解决方案是首先启动进程 B。然后将进程B 的进程ID 传递给进程A。使用它您可以终止进程。

def a(pid):
    os.kill(pid)

B = Process(target=b, args=())

A = Process(target=a,args=(B.pid))

选项 2: 为此,您可以使用队列或管道(来自 multiprocessing library )。

from multiprocessing import Process, Queue

def f(q):
     # will send the process id of the alternative child process 
     print q.get()

if __name__ == '__main__':
    queue_A = Queue()
    queue_B = Queue()
    A = Process(target=f, args=(queue_A,))
    B = Process(target=f,args=(queue_B,))
    A.start()
    B.start()

    queue_A.put(B.pid)
    queue_B.put(A.pid)
    # do stuff....

选项 3(我的首选方法): 获取主进程来执行终止操作。

A = Process(target=a, args=())

B = Process(target=b,args=())

A.terminate()
B.terminate()

关于python - 使用python多处理,子进程如何终止另一个子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30050690/

相关文章:

python - 无法使用 Tkinter 打印出 "event.char"

python - 将多个 Excel 文件加载到 Pandas 中

python - pip 无法安装 install_requires 中列出的软件包

python - 如何让 Beautiful Soup 输出 HTML 实体?

Python MQTT 回调未调用

python - Beautiful Soup 打开所有带有 pid 的 url

python - __init__.py imports 还暴露了我使用的模块,而不仅仅是我自己的类

python - 将字符串大写

python - 以编程方式使用特定于 Sphinx 的指令解析 .rst 文件

python - 如何抓取网络新闻并将段落合并到每篇文章中