我如何知道子进程何时死亡?
在我的课堂上我运行了 4 个进程。
from multiprocessing import Process
procs = (
Process(target=ClassOne, name='ClassOne'),
Process(target=ClassTwo, name='ClassTwo'),
Process(target=ClassThree, name='ClassThree'),
Process(target=ClassFour, name='ClassFour'),
)
for p in procs:
p.daemon = False
p.start()
当我的一个子进程死亡时,我希望收到通知,这样我就可以杀死另一个进程和我自己。
In my class I run 4 process.
from multiprocessing import Process
procs = (
Process(target=ClassOne, name='ClassOne'),
Process(target=ClassTwo, name='ClassTwo'),
Process(target=ClassThree, name='ClassThree'),
Process(target=ClassFour, name='ClassFour'),
)
for p in procs:
p.daemon = False
p.start()
I would like to be notified when one of my children process died so i can kill the other and my self.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只需为 SIGCHLD 定义一个信号处理程序,检查刚刚死亡的子级返回的帧以检索您需要的有关它的信息......如果需要,也可以退出()父级:)
Just define a signal handler for SIGCHLD, inspect the frame returned by the just dead child to retrieve the information you need about it ... and if necessary exit() the parent too :)
可以使用 os.waitpid() 传递 -1 作为第一个参数,将 0 作为第二个参数。
wait()
。该函数返回一个元组,其中包含已死亡子进程的 pid 及其退出代码。
It is possible to use
os.waitpid()
passing -1 as the first argument and 0 as the second one.wait()
.The function returns a tuple with the pid of the dead child and its exit code.
您可能想查看
如果您准备在代码中添加对 gobject(PyGTK 的一部分)的依赖项,那么 AutoJoiningProcess 将允许您监听进程完成时发出的信号。收到该信号后,您可以随心所欲地做出反应。
You might like to look at the class AutoJoiningProcess in the answer to this similar question.
If you're prepared to add to your code a dependency to gobject (part of PyGTK) then AutoJoiningProcess would allow you can listen to a signal that is emitted when a process finishes. On that signal you could then respond however you'd like.
最简单的方法是显式等待所有进程完成。
这不是您可能想要的事件驱动的,但它会在您的示例中完成工作。另请确保
导入多处理
。The simplest way would be to explicitly wait until all processes are done.
This is not event driven as you might intend, but it will get the job done in your example. Also make sure you
import multiprocessing
.这是一个 Windows 解决方案。它使用 WaitForMultipleObjects API 调用。对于 Unix os.waitpid 可以完成这项工作。
Here is a Windows solution. It uses WaitForMultipleObjects API call. For Unix os.waitpid may do the job.