【问题标题】:Default signal handling in PythonPython 中的默认信号处理
【发布时间】:2021-06-16 08:15:33
【问题描述】:

我想注册一个自定义信号处理程序,它会做一些事情,然后继续正常的信号处理,特别是针对 SIGTERM 信号。

Python 没有注册 SIGTERM 处理程序 (Python: What is the default handling of SIGTERM?),那么在我进行自己的自定义处理后,如何继续操作系统的正常 SIGTERM 处理?

def my_handler(self, signum, frame):
    do_something()
    # What do I do here to raise to the OS?

signal.signal(signal.SIGTERM, my_handler)

【问题讨论】:

    标签: python signals


    【解决方案1】:

    如果致命信号之前的处置是默认的,那么您能做的最好的事情就是恢复该处置并重新发出信号。

    这至少会导致你的进程异常终止,这样它的父进程就可以知道是哪个信号杀死了它(os.WIFSIGNALED)。如果致命信号有一个"additional action" 就像一个核心文件,这种模仿就不会完美。

    orig_handler = signal.signal(signal.SIGTERM, my_handler)
    
    def my_handler(signum, frame):
      do_something()
    
      # Now do whatever we'd have done if
      # my_handler had not been installed:
    
      if callable(orig_handler):              # Call previous handler
        orig_handler(signum, frame)
      elif orig_handler == signal.SIG_DFL:    # Default disposition
        signal.signal(signum, signal.SIG_DFL)
        os.kill(os.getpid(), signum)
                                              # else SIG_IGN - do nothing
    

    对于停止进程的信号(例如,SIGTSTP)或默认忽略(SIGCHLD、SIGURG)的信号,上述重新引发的信号不够细致。

    【讨论】:

    • 问题是,python没有SIGTERM的信号处理程序
    • @C_Z_ 那么信号处理将是默认值,即 SIG_DFL,您可以按上述方式处理。 (上面还处理了一个程序,它在设置信号处理之前安装自己的处理程序。)
    【解决方案2】:

    您想保存之前的默认值,如下所示:

    def my_handler(self, signum, frame):
        global original_sig_handler # Doesn't really matter if you do it as global or something else, you just need  the function to get here
        do_something()
        original_sig_handler()
    
    original_sig_handler = signal.getsignal(signal.SIGINT) # this return the function that called by handling the signal
    signal.signal(signal.SIGINT, my_handler)
    

    编辑:

    这不适用于sigterm,但适用于少数其他信号。

    可能为sigterm python 做一些sys.exit 或等等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      • 2014-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多