问题描述
我希望在终止原始进程后让进程继续运行.
I'm looking to leave a process running after terminating the original process.
以下代码在杀死原件后不会保持其进程运行.
The following code will not keep it's process running after killing the original.
args = ['yes']
Popen(args, shell=True, stdout=None, stdin=None, stderror=None)
我已经尝试了我能想到的所有方法,我使用了 os.spawn() 的变体,但无法让它们保持打开状态.
I've tried everything I can think of, I've used variations of os.spawn() and could not get them to stay open.
似乎向子进程发送了键盘中断(命令是).
It seems to send a keyboard interrupt to the child process(the command yes).
推荐答案
问题是,即使您的子进程无法通过标准流访问控制台,它仍然有一个控制终端em>;进程可以从其控制终端接收诸如 TSTP (stop, ^Z) 和 INT (^C) 之类的信号.因此,您想要的是将进程与控制终端和整个会话分离.执行此操作后,您将拥有一个适当的守护进程.
The problem is that even though your subprocess doesn't have access to the console via the standard streams, it will still have a controlling terminal; a process can receive signals such as TSTP (stop, ^Z) and INT (^C) from its controlling terminal. Therefore what you want to have is to detach the process from the controlling terminal and the entire session. When you do this, you'll have a proper daemon process.
在 C 世界和 Python 2 中,您可以通过调用 setsid 来实现这一点
在 child 进程中,这将为子进程创建一个新会话.此外,新会话将没有控制终端.
In C world and in Python 2 you can achieve this by calling setsid
in the child process, which will create a new session for the child process. Additionally the new session will not have a controlling terminal.
在 Python 3.2+ 中,这更容易 - 只需将 start_new_session=True
传入 Popen
:
In Python 3.2+ this is even easier - just pass in start_new_session=True
to the Popen
:
如果 start_new_session
为真,setsid()
系统调用将在子进程执行之前在子进程中进行.(仅限 POSIX)
在 3.2 版中更改:添加了 start_new_session
.
Changed in version 3.2: start_new_session
was added.
这篇关于关闭python后让进程继续运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!