39

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?

Rowan
  • 874
  • 1
  • 6
  • 14

4 Answers4

54

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))
milahu
  • 2,447
  • 1
  • 18
  • 25
Jason Martens
  • 1,305
  • 11
  • 22
4

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.

Zac Bowling
  • 6,508
  • 1
  • 27
  • 26
  • 3
    Yeah, 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
  • 1
    Actually 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
    Natim, your problem has nothing to do with this question. – Zac Bowling Nov 07 '12 at 19:23
2

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()]
Don Kirkby
  • 53,582
  • 27
  • 205
  • 286
1

Using psutil you can get all children process (even recursive process) look at https://psutil.readthedocs.io/en/latest/#psutil.Process.children

warvariuc
  • 57,116
  • 41
  • 173
  • 227
Ravi Gadhia
  • 490
  • 3
  • 11