简体   繁体   中英

Python : get child process pid and add to dictionary with parent process id

My application creates a pid file with details of parent pid in it. I have got a task to need to identify all the child pids associated with parent pid and store in dictionary format to a log.

I have written below script, in that i am able to get the parent pid with file name in dictionary. But stuck in a place in getting the the details of child pid in the output.

Python version: 2.6

To get the child process id used below function

def child(pid):
        process = subprocess.Popen(['pgrep','-P', str(pid) ], stdout=subprocess.PIPE,universal_newlines=True)
        output = process.communicate()
        return output

Child returns output in format

('12345','45678', None)

But unsure how to add the returned values to the existing dictionary.

Sample input file

cat file 1 
39007

cat file 2 
39023

Tried Script

           files=["file1", "file2" ]
           pids={}
           for pid_file in files:
                   try:
                           with open(pid_file, 'r') as f:
                                   al_pid = f.readline().strip()
                                   child(pid)
                                   pids[pid_file]=al_pid
                           f.close()
                   except:
                           print("Unable to open : " + pid_file + ". Skipping file")
   
           return pids

recieved Output

{'file': '39007','file2': '39023'}

Expected output

{'file': [39007, child_pid1, child_pid2],'file2': [39023, child_pid3, child_pid4]}

I'd recommend using process_iter in psutil and play with it a little:

from psutil import process_iter

for proc in process_iter():
    print(proc)
import psutil
processID = 11111
current_process = psutil.Process(processID)
print(current_process)
children = current_process.children(recursive=True)
print(children)
for child in children:
    print("Child pid is {}".format(child.pid))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM