Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to kill subprocesses when parent exits in python?

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 ?

like image 657
arc000 Avatar asked Sep 05 '25 16:09

arc000


1 Answers

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.

like image 167
Aaron Digulla Avatar answered Sep 07 '25 17:09

Aaron Digulla