如何阻止python将信号传播到子进程? [英] How to stop python from propagating signals to subprocesses?
问题描述
我正在使用 python 来管理一些模拟.我构建参数并使用以下命令运行程序:
I'm using python to manage some simulations. I build the parameters and run the program using:
pipe = open('/dev/null', 'w')
pid = subprocess.Popen(shlex.split(command), stdout=pipe, stderr=pipe)
我的代码处理不同的信号.Ctrl+C 会停止模拟,询问是否要保存,然后优雅退出.我有其他信号处理程序(例如强制数据输出).
My code handles different signal. Ctrl+C will stop the simulation, ask if I want to save, and exit gracefully. I have other signal handlers (to force data output for example).
我想要的是向我的 python 脚本发送一个信号(SIGINT、Ctrl+C),它会询问用户他想向程序发送哪个信号.
What I want is to send a signal (SIGINT, Ctrl+C) to my python script which will ask the user which signal he wants to send to the program.
阻止代码工作的唯一原因是无论我做什么,Ctrl+C 都会转发"到子进程:代码将捕获它并退出:
The only thing preventing the code to work is that it seems that whatever I do, Ctrl+C will be "forwarded" to the subprocess: the code will catch it to and exit:
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.我该怎么做???
So whatever I do, the program is receiving the SIGINT that I only want my python script to see. How can I do that???
我也试过:
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.
to run the program but this gives the same result: the program catches the SIGINT.
谢谢!
推荐答案
结合其他一些可以解决问题的答案 - 发送到主应用程序的信号不会被转发到子进程.
Combining some of other answers that will do the trick - no signal sent to main app will be forwarded to the subprocess.
import os
from subprocess import Popen
def preexec(): # Don't forward signals.
os.setpgrp()
Popen('whatever', preexec_fn = preexec)
这篇关于如何阻止python将信号传播到子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!