python - 如何阻止python将信号传播到子进程?

标签 python subprocess signals

我正在使用 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/

相关文章:

python - 如何找到椭圆的方程式

c - 有没有办法将 sigaction() 发送到具有多个参数的信号处理程序?

python - 如何在 Ubuntu docker 镜像中安装 Python2.7.5?

python - 使用子进程和 .Popen 自动执行 .exe 程序的简单 Windows 示例

python - tail 命令没有给出 subprocess.Popen 的正确答案

python - 子进程 Popen 和 call 有什么区别(我该如何使用它们)?

c# - .NET Framework 中的同步原语 : which one is the good one?

c++ - 从 cin 读取的进程上的 HUP 信号

python - Pygame:get_at 始终返回 'None'

python - 进入子目录、运行命令然后返回的最优雅的方式是什么?