【问题标题】:how can i receive a signal when a Popen terminates?Popen 终止时如何接收信号?
【发布时间】:2011-07-11 01:29:44
【问题描述】:

在 python 中,我有一个生成的 shell 进程,我可能会手动停止它,或者它可能会在感觉需要时自行终止。我可以在不一直轮询的情况下收到它已完成的通知吗?

class Foo(object):

  def __init__(self):
    self.running = False

  def start(self):
    import os
    from subprocess import Popen, PIPE
    self.proc = Popen(['foo'], stdout=PIPE, shell=True, preexec_fn=os.setsid)
    self.running = True

  def stop(self):
    if not self.running:
      print 'already stopped'
    else:
      import os, signal
      os.killpg(self.proc.pid, signal.SIGINT)
      self.on_complete()

  def on_complete(self):
    self.running = False

结构或多或少类似于上面。我的问题是,如果进程正常终止,而不是我自己的中断,那么self.running 仍然是True,所以我不能依赖该属性来处理类中的其他逻辑。

有没有一种简单的方法可以在正常终止的情况下调用on_complete,或者这首先是一个愚蠢的设计?

【问题讨论】:

    标签: python shell signals popen terminate


    【解决方案1】:

    您应该能够为SIGCHLD 安装处理程序。不过,请仔细阅读文档;通过注册对该信号的兴趣,您承诺在信号处理程序中处理子进程; waits 在子进程本身上的任何东西都会阻塞,直到所有正在运行的子进程都被信号处理程序处理,然后出错。这包括system()Popen 自己的子进程清理。 (例如,请参阅Popen.communicate() throws OSError: "[Errno 10] No child processes"。)

    【讨论】:

      猜你喜欢
      • 2017-05-07
      • 2018-02-20
      • 1970-01-01
      • 2011-09-11
      • 1970-01-01
      • 2018-12-21
      • 1970-01-01
      • 2015-05-24
      • 1970-01-01
      相关资源
      最近更新 更多