在另一个进程中运行程序并在 Python 中接收 pid [英] Run program in another process and receive pid in Python

查看:31
本文介绍了在另一个进程中运行程序并在 Python 中接收 pid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在另一个进程中运行一个程序,得到这个程序的pid,子进程不应该依赖于父进程.请参阅以下 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 &')

但在这种情况下,我无法获得子进程 pid.
如何在另一个进程中运行一个程序,获取该程序和子进程不应该依赖于父进程的pid?

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?

推荐答案

您遇到了 Unix 进程组管理问题.特别是,当您在连接到终端时杀死进程组的会话领导者(如您的脚本),该组中的所有进程都会收到 SIGHUP,默认情况下会导致终止.

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.

一种解决方案是使用os.setsid() 为子进程建立一个新会话.在 Python 3 中 subprocess.Popen() 接受一个 start_new_session=True 为你做这件事.对于 Python 2,我们可以使用 preexec_fn 获得类似的解决方案:

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)

这篇关于在另一个进程中运行程序并在 Python 中接收 pid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆