Reputation: 893
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 ?
Upvotes: 4
Views: 7857
Reputation: 414745
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.
Upvotes: 0
Reputation: 328770
Children don't automatically die when the parent process is killed. They die if:
The signals
module contains examples how to write a signal handler.
So you need to:
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.
Upvotes: 6