开发者

how can i receive a signal when a Popen terminates?

in python, i have a spawned shell process which i might stop manually , or it might terminate itself when it feels like it. can i receive开发者_运维技巧 a notification that it has completed, without polling it all the time?

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

the construct is more or less like the above. my problem is that if the process was terminated normally, not by my own interrupt , then self.running remains True so i can not rely on that attribute for other logic in the class.

is there a simple way to have on_complete called for the case of normal termination, or is this a silly design in the first place?


You should be able to install a handler for SIGCHLD. Read the documentation carefully, though; by registering interest in that signal, you are committing to handling child processes in the signal handler; anything that waits on the subprocess itself will block until all running children have been processes by the signal handler and then error out. This includes system() and Popen's own subprocess cleanup. (See Popen.communicate() throws OSError: "[Errno 10] No child processes", for example.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜