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
def child(pid):
process = subprocess.Popen(['pgrep','-P', str(pid) ], stdout=subprocess.PIPE,universal_newlines=True)
output = process.communicate()
return output
def get_pids(market):
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")
print pids
recieved Output
{'file': '39007','file2': '39023'}
Expected output
{'file': [39007, child_pid1, child_pid2],'file2': [39023, child_pid3, child_pid4]}
I can resolve my problem with the below code.
files=['file','file2']
pids={}
def child(pid):
process = subprocess.Popen(['pgrep','-P', str(pid) ], stdout=subprocess.PIPE)
output = process.stdout.readlines()
out=[p.strip() for p in output]
return out
for pid_file in files:
with open(pid_file, 'r') as f:
al_pid = f.readline().strip()
pid=child(al_pid)
pid.insert(0,al_pid)
pids[pid_file]=pid
f.close()
print pids