Python 在关闭主进程时关闭子进程
我有一个主进程,它派生了许多子进程。当我的主进程收到终止信号时,我希望能够终止这些子进程。理想情况下,我想做一些类似的事情:
def handler(signum, frame, pid_list):
log('Killing Process')
for pid in pid_list:
os.kill(pid, signal.SIGTERM)
os.waitpid(pid, 0) # need
sys.exit()
if __name__ == "__main__":
<code that creates child processes, pids>
signal.signal(signal.SIGTERM, handler(pid_list))
但是当然,这不起作用......有什么建议吗?
I have have a main process that forks a number of subprocesses. I want to be able to kill these child processes off when my main process gets the kill signal. Ideally I would want to do something along the lines of:
def handler(signum, frame, pid_list):
log('Killing Process')
for pid in pid_list:
os.kill(pid, signal.SIGTERM)
os.waitpid(pid, 0) # need
sys.exit()
if __name__ == "__main__":
<code that creates child processes, pids>
signal.signal(signal.SIGTERM, handler(pid_list))
But of course, that doesn't work... any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 @tony 建议 你可以设置
使用
标志。要在 python2.4 上安装它,请输入:multiprocessing
模块创建的子进程上的 daemon=Truepip install multiprocessing
。如果主进程被信号杀死,子进程将不会被终止,因此您需要提供适当的信号处理程序:
As @tony suggested you could set
daemon=True
flag on a child process created usingmultiprocessing
module. To install it on python2.4, type:pip install multiprocessing
.The child processes won't be terminated if the main process is killed by a signal so you need to provide an appropriate signal handler:
创建子进程时使用 this 标志怎么样?
What about use this flag when you create a subprocess?