问题描述
我目前正在为在 shell 中运行的专用服务器开发一个包装器.包装器通过子进程生成服务器进程并观察其输出并对其做出反应.
I am currently working on a wrapper for a dedicated server running in the shell. The wrapper spawns the server process via subprocess and observes and reacts to its output.
必须明确地给专用服务器一个命令才能正常关闭.因此,CTRL-C 不能到达服务器进程.
The dedicated server must be explicitly given a command to shut down gracefully. Thus, CTRL-C must not reach the server process.
如果我在 python 中捕获 KeyboardInterrupt 异常或覆盖 SIGINT 处理程序,服务器进程仍会收到 CTRL-C 并立即停止.
If I capture the KeyboardInterrupt exception or overwrite the SIGINT-handler in python, the server process still receives the CTRL-C and stops immediately.
所以我的问题是:如何防止子进程接收到 CTRL-C/Control-C/SIGINT?
So my question is: How to prevent subprocesses from receiving CTRL-C / Control-C / SIGINT?
推荐答案
#python IRC-Channel (Freenode) 有人帮我指出了 subprocess.Popen 的 preexec_fn 参数(...):
Somebody in the #python IRC-Channel (Freenode) helped me by pointing out the preexec_fn parameter of subprocess.Popen(...):
如果 preexec_fn 设置为可调用对象,这个对象将被调用子进程就在孩子被处决.(仅限 Unix)
If preexec_fn is set to a callable object, this object will be called in the child process just before the child is executed. (Unix only)
因此,以下代码解决了这个问题(仅限 UNIX):
Thus, the following code solves the problem (UNIX only):
import subprocess
import signal
def preexec_function():
# Ignore the SIGINT signal by setting the handler to the standard
# signal handler SIG_IGN.
signal.signal(signal.SIGINT, signal.SIG_IGN)
my_process = subprocess.Popen(
["my_executable"],
preexec_fn = preexec_function
)
注意:信号实际上并没有被阻止到达子进程.相反,上面的 preexec_fn 会覆盖信号的默认处理程序,从而忽略信号.因此,如果子进程再次覆盖 SIGINT 处理程序,此解决方案可能不起作用.
Note: The signal is actually not prevented from reaching the subprocess. Instead, the preexec_fn above overwrites the signal's default handler so that the signal is ignored. Thus, this solution may not work if the subprocess overwrites the SIGINT handler again.
另一个注意事项:此解决方案适用于各种子流程,即它也不限于用 Python 编写的子流程.例如,我正在为其编写包装器的专用服务器实际上是用 Java 编写的.
Another note: This solution works for all sorts of subprocesses, i.e. it is not restricted to subprocesses written in Python, too. For example the dedicated server I am writing my wrapper for is in fact written in Java.
这篇关于Python:如何防止子进程接收 CTRL-C/Control-C/SIGINT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!