how to kill subprocesses when parent exits in python?

六月ゝ 毕业季﹏ 提交于 2021-02-04 21:26:04

问题


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

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 ?


回答1:


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

  • The parent forwards the signal and waits for the children to terminate
  • When the child tries to communicate with the parent, for example via stdio. That only works if the parent also created the file descriptors which the child uses.

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

So you need to:

  • collect all children in a list
  • install a signal handler
  • in the handler, iterate over all the child processes
  • For each child process, invoke child.terminate() followed by child.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.




回答2:


A simple way to kill the whole process tree in the shell is to kill its process group i.e., instead of kill $pid, run:

$ kill -TERM -$pid

Notice: the pid is negated.

Shell creates a new process group for each command (pipeline) therefore you won't kill innocent bystanders.

If descendant processes do not create their own independent process groups; they all die.

See Best way to kill all child processes.



来源:https://stackoverflow.com/questions/28025402/how-to-kill-subprocesses-when-parent-exits-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!