如何优雅地处理SIGTERM信号?如何优雅地处理SIGTERM信号?(How to process

2019-05-08 18:54发布

假设我们有Python编写这样一个微不足道的守护程序:

def mainloop():
    while True:
        # 1. do
        # 2. some
        # 3. important
        # 4. job
        # 5. sleep

mainloop()

我们守护进程使用它start-stop-daemon在默认情况下发送SIGTERMTERM上)信号--stop

让我们假设执行当前步骤是#2 。 而在这个非常时刻,我们要发送TERM信号。

什么情况是,执行立即终止。

我发现我可以使用处理信号事件signal.signal(signal.SIGTERM, handler) ,但事情是,它仍然中断当前执行并传递控制handler

所以,我的问题是-它可以不中断当前执行,但处理TERM在一个独立的线程,这样我能够设置信号(?) shutdown_flag = Truemainloop()有机会停止正常?

Answer 1:

基于清洁使用的解决方案类:

import signal
import time

class GracefulKiller:
  kill_now = False
  def __init__(self):
    signal.signal(signal.SIGINT, self.exit_gracefully)
    signal.signal(signal.SIGTERM, self.exit_gracefully)

  def exit_gracefully(self,signum, frame):
    self.kill_now = True

if __name__ == '__main__':
  killer = GracefulKiller()
  while True:
    time.sleep(1)
    print("doing something in a loop ...")
    if killer.kill_now:
      break

  print "End of the program. I was killed gracefully :)"


Answer 2:

首先,我不能确定是否需要第二个线程设置shutdown_flag。 为什么不直接在SIGTERM处理器设置呢?

另一种方法是提高从一个异常SIGTERM处理程序,这将在传播堆栈。 假设你有适当的异常处理(例如用with / contextmanagertry: ... finally:块),这应该是一个相当正常关机,类似于如果你要Ctrl-C程序。

实施例程序signals-test.py

#!/usr/bin/python

from time import sleep
import signal
import sys


def sigterm_handler(_signo, _stack_frame):
    # Raises SystemExit(0):
    sys.exit(0)

if sys.argv[1] == "handle_signal":
    signal.signal(signal.SIGTERM, sigterm_handler)

try:
    print "Hello"
    i = 0
    while True:
        i += 1
        print "Iteration #%i" % i
        sleep(1)
finally:
    print "Goodbye"

现在看到的按Ctrl-C行为:

$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
^CGoodbye
Traceback (most recent call last):
  File "./signals-test.py", line 21, in <module>
    sleep(1)
KeyboardInterrupt
$ echo $?
1

这一次,我把它SIGTERM后4次迭代kill $(ps aux | grep signals-test | awk '/python/ {print $2}')

$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Terminated
$ echo $?
143

这一次,我让我的自定义SIGTERM处理器,并将其发送SIGTERM

$ ./signals-test.py handle_signal
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Goodbye
$ echo $?
0


Answer 3:

我认为你是附近的一个可能的解决方案。

执行mainloop在一个单独的线程,并与物业扩展它shutdown_flag 。 该信号可以与被捕获signal.signal(signal.SIGTERM, handler)在主螺纹(未在单独的线程)。 信号处理程序应该设置shutdown_flag为真,并等待线程来结束thread.join()



Answer 4:

这里是没有螺纹或类的简单示例。

import signal

run = True

def handler_stop_signals(signum, frame):
    global run
    run = False

signal.signal(signal.SIGINT, handler_stop_signals)
signal.signal(signal.SIGTERM, handler_stop_signals)

while run:
    pass # do stuff including other IO stuff


Answer 5:

根据前面的答案,我创建了从SIGINT和SIGTERM保护上下文管理。

import logging
import signal
import sys


class TerminateProtected:
    """ Protect a piece of code from being killed by SIGINT or SIGTERM.
    It can still be killed by a force kill.

    Example:
        with TerminateProtected():
            run_func_1()
            run_func_2()

    Both functions will be executed even if a sigterm or sigkill has been received.
    """
    killed = False

    def _handler(self, signum, frame):
        logging.error("Received SIGINT or SIGTERM! Finishing this block, then exiting.")
        self.killed = True

    def __enter__(self):
        self.old_sigint = signal.signal(signal.SIGINT, self._handler)
        self.old_sigterm = signal.signal(signal.SIGTERM, self._handler)

    def __exit__(self, type, value, traceback):
        if self.killed:
            sys.exit(0)
        signal.signal(signal.SIGINT, self.old_sigint)
        signal.signal(signal.SIGTERM, self.old_sigterm)


if __name__ == '__main__':
    print("Try pressing ctrl+c while the sleep is running!")
    from time import sleep
    with TerminateProtected():
        sleep(10)
        print("Finished anyway!")
    print("This only prints if there was no sigint or sigterm")


Answer 6:

我发现最简单的方法。 这里与叉为了清楚的例子,这种方法是用于流控制是有用的。

import signal
import time
import sys
import os

def handle_exit(sig, frame):
    raise(SystemExit)

def main():
    time.sleep(120)

signal.signal(signal.SIGTERM, handle_exit)

p = os.fork()
if p == 0:
    main()
    os._exit()

try:
    os.waitpid(p, 0)
except (KeyboardInterrupt, SystemExit):
    print('exit handled')
    os.kill(p, 15)
    os.waitpid(p, 0)


文章来源: How to process SIGTERM signal gracefully?