0

Scenario: subprocess created a subprocess and so on, how can i get it's pid?

I used subprocess.popen to launch the first subprocess, for example word file, this word file generated a new subprocess, how can i get it's pid?

Nikaido
  • 4,443
  • 5
  • 30
  • 47
MichaelK
  • 189
  • 2
  • 11
  • Possible duplicate of [Opening a process with Popen and getting the PID](http://stackoverflow.com/questions/7989922/opening-a-process-with-popen-and-getting-the-pid) – Ari Gold Nov 09 '16 at 14:55
  • did you even read the question? i asked for the inner pid – MichaelK Nov 09 '16 at 14:59
  • yes sure, if you have the pid of the root process, you can ask for the nested pid's by calling pstree from your module, pstree -p $pid(root_process_pid) | grep -o '([0-9]\+)' | grep -o '[0-9]\+' http://unix.stackexchange.com/questions/67668/elegantly-get-list-of-descendant-processes – Ari Gold Nov 09 '16 at 15:09
  • 1
    Once you got the pid of the main process, using `psutil` is probably the easiest way to traverse the process tree in python: https://stackoverflow.com/questions/3332043/obtaining-pid-of-child-process – languitar Nov 09 '16 at 15:20
  • thank you for the explanation yet it didn't help me tried parent = psutil.Process(proc.pid).parent() for child in parent.children(recursive=True): print 'parent %d child %d' % (proc.pid,child.pid) and without the parent(), it didn't help, i couldn't get the childs pid the only pid that i get is the father's – MichaelK Nov 09 '16 at 16:03

1 Answers1

1

Using psutil:

parent = psutil.Process(parent_pid)
children = parent.children()
# all child pids can be accessed using the pid attribute
child_pids = [p.pid for p in children]
languitar
  • 6,554
  • 2
  • 37
  • 62
  • it doesn't help :( child_pids appears to be always empty(even though child processes do appear) – MichaelK Nov 09 '16 at 16:11
  • 1
    Then your process uses some technique to detach from the child. You can also use psutil to find the parent pid of the subprocess. Maybe this helps to discover what happens. – languitar Nov 09 '16 at 16:24