Does python provide a way to find the children of a child process spawned using subprocess, so that I can kill them properly? If not, what is a good way of ensuring that the children of a child are killed?
-
Not quite a duplicate of this (as it simply says don't invoke the shell. I'm looking for a way to get the children of spawned subprocess, the python spawned process is already being invoked directly) : http://stackoverflow.com/questions/2638909/killing-a-subprocess-including-its-children-from-python – archgoon Feb 02 '12 at 18:15
2 Answers
The following applies to Unix only:
Calling os.setsid() in the child process will make it the session leader of a new session and the process group leader of a new process group. Sending a SIGTERM to the process group will send a SIGTERM to all the subprocess that this child process might have spawned.
You could do this using subprocess.Popen(..., preexec_fn=os.setsid)
. For example:
import signal
import os
import subprocess
import time
PIPE = subprocess.PIPE
proc = subprocess.Popen('ls -laR /', shell=True,
preexec_fn=os.setsid,
stdout=PIPE, stderr=PIPE)
time.sleep(2)
os.killpg(proc.pid, signal.SIGTERM)
Running this will show no output, but ps ax
will show the subprocess and the ls -laR
that it spawns are terminated.
But if you comment out
preexec_fn=os.setsid
then ps ax
will show something like
% ps ax | grep "ls -la"
5409 pts/3 S 0:00 /bin/sh -c ls -laR /
5410 pts/3 R 0:05 ls -laR /
So without os.setsid
, ls -laR
and the shell that spawned it are still running. Be sure to kill them:
% kill 5409
% kill 5410

- 842,883
- 184
- 1,785
- 1,677
-
Thanks, this helped me a lot with killing a subprocess that spawned its own processes. – flinz Apr 08 '16 at 08:54
Not exactly easy, but if your application runs in Linux, you could walk through the /proc filesystem and build a list of all PIDs whose PPID (parent PID) is the same as your subprocess'.

- 362
- 1
- 2
- 13
-
Sigh. So I take it the answer is effectively no. Thank you. I'll see if I can avoid subprocess spawns (or get them killed automatically). – archgoon Feb 02 '12 at 20:54