Get pid of recursive subprocesses - python

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?

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]

Related

How to change a processes' STDIN to the STDOUT of another process during runtime

How can I change a python script's STDIN to be the STDOUT of another process in the middle of the runtime of that script?
I'm writing a python application that runs as a non-root user and that launches a child process as root using subprocess. Due to complexities in how MacOS handles privilege escalation, the child process's parent process is no longer the python script that created it, the child looses its tty, and the stdin/stdout communication gets broken between parent & child.
Since the child process is root, I can find the actual parent processes' PID and TTY using ps
result = os.popen( 'ps -eo "pid, tty, command" | grep -iE "[s]pawn_root.py"' ).read().splitlines().pop().split()
pid = result[0]
tty = result[1]
And I was successfully able to attach the stdin of the child process to the tty of the parent process as follows
sys.stdin = open( '/dev/' +str(tty), 'r' )
Unfortunately, it seems that attaching to the tty of the parent process is not the same as attaching to the STDOUT of the parent process. I guess it's a path to a different file descriptor, somehow.
If I have a python process A running as root on MacOS, how can I attach that processes' STDIN to the STDOUT of process B, given the PID or Command name of process B?

How to get parent child relationship in python

I have multiple executable files running in the server in different ways either from the task scheduler or from the controller, which is not appropriate now i have to change this using python
I need to write a python script which can initiate the executables as a separate process which holds the parent process ID to form a parent-child relationship, to do this i have used multiprocessing and subprocess
import multiprocessing
import subprocess
def Do_Something():
exe_str = r"C:/Users/De/desktop/CreateFileWithCurrentDate.exe"
C_Pro = subprocess.Popen(exe_str, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print(C_Pro.pid)
# To get list of all the process running
processes = []
if __name__ == '__main__':
for i in range(5): # Looping through to create multiple process based on the range with parent child Process
p = multiprocessing.Process(target=Do_Something) # Mechanism to create multiple process
p.start() #Start the process async
processes.append(p) #Adding all the created process to the list
print(f'Parent Process ID: {p._parent_pid}, New Child Process ID: {p.pid}')
Here i am able to create multiple processes using the multiprocessing module, like a single parent and multiple children, but the actual problem is when i am triggering the method Do_Something as a process inside which i am using subprocess module which is again creating another process, this shouldn't be the case as the executable should be the child process ID which is created using multiprocessing module
Please help me out in this to archive multiprocessing using parent and child relationship
thanks

Is there a way to get just the pid of a process with its name for the purpose of suspending it for a set time

I need to gain the pid of a program in order to suspend it temporarily. How can I gain the pid of a program using python with just its username in order to use this pid along with psutil to suspend the process? Let's just call it process.exe for now.
I have tried using item for item along with psuti. However, this gives me additional text along with the pid and I am unsure how to remove this unnecesary text.
I have tried using os.getpid but this gives me the pid of Python rather than the process I want to get the pid of.
1.
import psutil
pid = [item for item in psutil.process_iter() if item.name() == 'process.exe']
print(pid)
2.
import os
pid = os.getpid()
print(pid)
For (1) I want the output to just be
pid=x
However, right now it is:
[psutil.Process(pid=x, name='process.exe', started='14:11:40')]
In 1, you are receiving process object which contains all the information about process, you can use the process object to fetch the pid:
pid[0].pid
In 2nd ,
os.getpid()
returns the process id of python interpreter and is of hardly any use under python interpreter, only use it when you are running some python script to get its process id.

python process creation and process ID

Can some one suggest what could be the best method to spawn a child process in python?
I have used one method like below.How can I get the pid of child process in below method ? Or how do I know the process been actually created ?
def main():
process = QtCore.QProcess()
process.start('python', ['./Hello_World.py'])
time.sleep(5)
process.kill()
How about using popen.
import subprocess
p = subprocess.Popen(['ls', '-alh'])
print(p.pid)
You can also use the instance to communicate with the spawned process.

Python multiprocessing. How do you get the status of the parent from the child?

I'm writing an application (Linux) using the multiprocessing module, which spawns several children. When a child dies, I can detect it from the parent using something like the following:
process = multiprocessing.Process(...)
if process.is_alive():
print "Process died"
However, I'd also like to be able to detect from the children if the parent is still alive, to handle cleanup if someone goes and kill -9's the parent process.
From my example above, I can get the parent id with either:
process._parent_pid
Or:
os.getppid()
But I can't find an easy way to get a status of the process. I'd rather not write something to grep/regex the ps list using subprocess. Is there a cleaner way?
You could compare the parent's process id against 1; if it is 1 then you can deduce the parent process has terminated, because the subprocess now has the init process (pid 1) as parent.
import os
import time
from multiprocessing import Process
def subprocess():
while True:
ppid = os.getppid()
print "Parent process id:", ppid
if ppid == 1:
print "Parent process has terminated"
break
time.sleep(1)
p = Process(target=subprocess)
p.start()

Categories