简体   繁体   中英

Run program in another process and receive pid in Python

I want to run a program in another process, get pid this program and child process should be not depended from parent. Please see following Python code:

cmd = 'myPythonProgramm -p param'
pid = subprocess.Popen(cmd, shell = True).pid

But if I kill parent process then also kill child process.
This issue is not exist if I use:

os.system('nohup myPythonProgramm -p param &')

But in this case I can't get child process pid.
How can I run a program in another process, get pid this program and child process should be not depended from parent?

You are running into Unix process group management. In particular, when you kill the session leader of a process group when it is attached to a terminal (as is your script), all processes in that group receive a SIGHUP , which by default causes termination.

One solution is to establish a new session for the child using os.setsid() . In Python 3 subprocess.Popen() accepts a start_new_session=True which does this for you. For Python 2, we can get a similar solution using preexec_fn :

subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid)

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