Python psutil doesn't show all child processes

I have a small python script that essentially looks like this:

import os
import psutil

def processtree():
    pid = os.getpid()
    # have to go two levels up to skip calling shell and 
    # get to actual parent process
    parent = psutil.Process(pid).parent().parent()

    print 'Parent %s [PID = %d]' % (parent.name(), parent.pid)
    print '        |'
    for child in parent.children(recursive=True):
        if child.pid != pid:
            print '        - Child %s [PID = %d]' % (child.name(), child.pid)
        else:
            print '        - Child %s [PID = %d] (Self)' % (child.name(), child.pid)

if '__name__' == '__main__':
    processtree()

      

When I run this script on bash

Windows, but nothing else works, I see the following:

Parent bash.exe [PID = 5984]
       |
       - Child bash.exe [PID = 5008]
       |
       - Child python.exe [PID = 3736] (Self)

      

This information is correct. The parent bash process is PID 5984 and the python process is 3736. Now I start sleep 10000 &

, so it works as a child of PID 5984. I check ps -aef | grep 5984

and it is there ;:

$ ps -aef | grep 5984 | grep -v grep | grep -v ps
myuser    5984       1 con    May 12 /bin/bash
myuser    5080    5984 con  11:17:12 /bin/sleep
myuser    3948    5984 con  11:36:47 /bin/bash

      

However, when I run my script again, it still shows:

Parent bash.exe [PID = 5984]
       |
       - Child bash.exe [PID = 7560]
       |
       - Child python.exe [PID = 5168] (Self)

      

It does not show sleep

as a child of the parent bash process, although it ps

does show it as present.

Note that the PID for the child of bash.exe has changed since the new call shell was created (not sure why this is happening, but I don't think it is related). The PID of the python interpreter because I called the script again python processtree.py

.

Not sure what I am doing wrong and I have been looking at this for a while. Any help is appreciated ...

+3


source to share


1 answer


Posting from comments so others don't see this as an unanswered open-ended question

You will need to use parent = psutil.Process(pid).parent()

.



On Unix, the combination of fork

and exec

results in the replacement of the second bash process with sleep.

Windows is based on the New Process Model, which is a legacy inherited from DEC VMS. (Dave Cutler managed design like the VMS, and NT. Many of the former DEC engineers followed him to Microsoft in 1988.) The kernel NT can actually realize fork

, and exec

what it does for the SUA subsystem .

+1


source







All Articles