我正在使用 python 来管理一些模拟。我使用以下方法构建参数并运行程序:
pipe = open('/dev/null', 'w')
pid = subprocess.Popen(shlex.split(command), stdout=pipe, stderr=pipe)
我的代码处理不同的信号。 Ctrl+C 将停止模拟,询问我是否要保存,然后优雅地退出。我还有其他信号处理程序(例如强制数据输出)。
我想要的是向我的 python 脚本发送一个信号(SIGINT,Ctrl+C),该脚本将询问用户他想向程序发送哪个信号。
阻止代码工作的唯一原因是,似乎无论我做什么,Ctrl+C 都会“转发”到子进程:代码会将其捕获并退出:
try:
<wait for available slots>
except KeyboardInterrupt:
print "KeyboardInterrupt catched! All simulations are paused. Please choose the signal to send:"
print " 0: SIGCONT (Continue simulation)"
print " 1: SIGINT (Exit and save)"
[...]
answer = raw_input()
pid.send_signal(signal.SIGCONT)
if (answer == "0"):
print " --> Continuing simulation..."
elif (answer == "1"):
print " --> Exit and save."
pid.send_signal(signal.SIGINT)
[...]
所以无论我做什么,程序都会收到我只想让我的 python 脚本看到的 SIGINT。我该怎么做???
我也试过了:
signal.signal(signal.SIGINT, signal.SIG_IGN)
pid = subprocess.Popen(shlex.split(command), stdout=pipe, stderr=pipe)
signal.signal(signal.SIGINT, signal.SIG_DFL)
运行程序,但这给出了相同的结果:程序捕获了 SIGINT。
谢谢!
最佳答案
结合其他一些可以解决问题的答案 - 发送到主应用程序的信号不会被转发到子进程。
import os
from subprocess import Popen
def preexec(): # Don't forward signals.
os.setpgrp()
Popen('whatever', preexec_fn = preexec)
关于python - 如何阻止python将信号传播到子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3791398/