双叉后Python中的信号处理

时间:2017-05-09 11:29:06

标签: python signals fork daemon

Python的奇怪行为在双叉之后创建一个类似教科书的守护进程。在分叉两次后在孙子中注册SIGTERM处理程序时,处理程序永远不会被调用信号接收到正确的PID,即。孙子之一。

可以找到完整代码here

import sys
import signal
import time
import os
import logging

class Handler(object):
    def __init__(self, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
        self.stdin = stdin
        self.stdout = stdout
        self.stderr = stderr

    def daemon(self):
          logging.debug('Before first fork')
          try:
              pid = os.fork()
              if pid > 0:
                  #exit first parent
                  sys.exit(0)
          except OSError, e:
                sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
                sys.exit(1)
          # decouple from parent environment
          logging.debug('After first fork')
          os.chdir("/")
          os.setsid()
          os.umask(0)

         # do second fork
         try:
             pid = os.fork()
             if pid > 0:
                  # exit from second parent
                 sys.exit(0)
          except OSError as e:
                 sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
                 sys.exit(1)
          # Redirect standard file descriptors
          logging.debug('After second fork')
          sys.stdout.flush()
          sys.stderr.flush()
          si = file(self.stdin, 'r')
          so = file(self.stdout, 'w+')
          se = file(self.stderr, 'w+', 0)
          os.dup2(si.fileno(), sys.stdin.fileno())
          os.dup2(so.fileno(), sys.stdout.fileno())
          os.dup2(se.fileno(), sys.stderr.fileno())
          logging.debug('before setting signal handlers')
          signal.signal(signal.SIGTERM, self.sigint_handler)
          logging.debug('before while')
          while True:
                sys.stdout.write('.')
                sys.stdout.flush()
                time.sleep(1)

     def sigint_handler(self, signum, frame):
           logging.debug('In signal handler')
           os.killpg(0, signal.SIGTERM)

def main():
     logging.basicConfig(filename='log', filemode='w',
     level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s')

     han = Handler()
     han.daemon()
     ##########

if __name__ == "__main__":
    main()

问题是什么?或者我只是错过森林的树木?

0 个答案:

没有答案