I am using python's multiprocessing module to spawn new process
as follows :
import multiprocessing
import os
d = multiprocessing.Process(target=os.system,args=('iostat 2 > a.txt',))
d.start()
I want to obtain pid of iostat command or the command executed using multiprocessing module
When I execute :
d.pid
it gives me pid of subshell in which this command is running .
Any help will be valuable .
Thanks in advance
For your example you may use the
subprocess
package. By default it executes the command without shell (likeos.system()
) and provides a PID:The
Popen
also provides ability to connect to standard input and output of the process.note: before using
shell=True
be aware of the security considerations.Since you appear to be using Unix, you can use a quick
ps
command to get the details of the child processes, like I did here (this is Linux-specific):I think with the multiprocess module you might be out of luck since you are really forking python directly and are given that Process object instead of the process you are interested in at the bottom of the process tree.
An alternative way, but perhaps not optimal way, to get that pid is to use the psutil module to look it up using the pid obtained from your Process object. Psutil, however, is system dependent and will need to be installed separately on each of your target platforms.
Note: I'm not currently at a machine I typically work from, so I can't provide working code nor play around to find a better option, but will edit this answer when I can to show how you might be able to do this.
Similar to @rakslice, you can use psutil:
This gave me the PID of
iostat
See image.