I'm using a third party library that starts various sub processes. When there's an exception I'd like to kill all the child processes. How can I get a list of child pids?
-
Might help to tell us your OS, since this is going to be platform dependent – John La Rooy Jul 02 '10 at 01:00
-
1Does POSIX help you? I assume some people would like to know the Windows answer too. – Rowan Jul 07 '10 at 23:09
-
See: http://stackoverflow.com/a/4229404/376587 – Giampaolo Rodolà Mar 11 '14 at 15:20
4 Answers
You can't always log all the sub-processes as they are created, since they can in turn create new processes that you are not aware of. However, it's pretty simple to use psutil to find them:
import psutil
current_process = psutil.Process()
children = current_process.children(recursive=True)
for child in children:
print('Child pid is {}'.format(child.pid))

- 2,447
- 1
- 18
- 25

- 1,305
- 11
- 22
It's usually safer to log the pids of all your child processes when you create them. There isn't a posix compliant way to list child PIDs. I know this can be done with the PS tool.

- 6,508
- 1
- 27
- 26
-
3Yeah, I expected that. The problem is it's not me creating the processes, it's the third party library. Oh well. It's not a showstopper. – Rowan Jul 03 '10 at 18:44
-
1Actually your answer is not the solution. I really needs to know how I can get ``psutil.Process`` to give me recursive ``memory_info`` and ``cpu_percent`` but my call to subprocess actually open other subprocess (at least 4 or 5 levels) an I have no way to keep a track of all the PIDs. – Natim Oct 24 '12 at 17:12
-
This give us a little more informations: http://stackoverflow.com/questions/3332043/obtaining-pid-of-child-process – Natim Oct 24 '12 at 17:16
-
1
It sounds like psutil is the recommended method. If, however, you don't want to depend on an external library, you can use the --ppid
of the ps
command to filter processes by parent id. (Assuming you're running on an OS with ps
, of course.)
Here's a snippet that shows how to call it:
ps_output = run(['ps', '-opid', '--no-headers', '--ppid', str(os.getpid())],
stdout=PIPE, encoding='utf8')
child_process_ids = [int(line) for line in ps_output.stdout.splitlines()]

- 53,582
- 27
- 205
- 286
Using psutil you can get all children process (even recursive process) look at https://psutil.readthedocs.io/en/latest/#psutil.Process.children

- 57,116
- 41
- 173
- 227

- 490
- 3
- 11