python - 当父进程退出时如何杀死子进程? [英] how to kill subprocesses when parent exits in python?

查看:89
本文介绍了python - 当父进程退出时如何杀死子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

fork_child.py 中的代码

code in fork_child.py

from subprocess import Popen
child = Popen(["ping", "google.com"], stdout=subprocess.PIPE,stderr=subprocess.PIPE)
out, err = child.communicate()

我从终端窗口运行它 -

I run it from a terminal window as -

$python fork_child.py

如果我从另一个终端窗口获取 fork_child.py 的 PID 并用 SIGTERM 杀死它,ping"不会被杀死.当 fork_child 收到 SIGTERM 时,如何确保 ping 也被终止?

From another terminal window if I get the PID of fork_child.py and kill it with SIGTERM, "ping" doesn't get killed. How do I make sure that ping too gets killed when fork_child receives a SIGTERM ?

推荐答案

当父进程被杀死时,子进程不会自动死亡.他们会在以下情况下死亡:

Children don't automatically die when the parent process is killed. They die if:

  • 父进程转发信号并等待子进程终止
  • 当孩子尝试与父母沟通时,例如通过 stdio.这仅在父级还创建了子级使用的文件描述符时才有效.

signals 模块包含示例如何编写信号处理程序.

The signals module contains examples how to write a signal handler.

所以你需要:

  • 收集列表中的所有孩子
  • 安装信号处理程序
  • 在处理程序中,遍历所有子进程
  • 对于每个子进程,调用 child.terminate() 后跟 child.wait()

wait() 是允许操作系统垃圾收集子进程所必需的.如果你忘记了它,你可能最终会遇到僵尸进程.

The wait() is necessary to allow the OS to garbage collect the child process. If you forget it, you may end up with zombie processes.

这篇关于python - 当父进程退出时如何杀死子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆