让我们假设我们用python编写了这样一个简单的守护进程:
def mainloop():
while True:
# 1. do
# 2. some
# 3. important
# 4. job
# 5. sleep
mainloop()
我们使用start-stop-daemon守护它,默认情况下发送SIGTERM (TERM)信号在——stop上。
让我们假设当前执行的步骤是#2。此时,我们发送TERM信号。
结果是执行立即终止。
我发现我可以使用signal.signal(信号。SIGTERM,处理程序),但问题是它仍然中断当前执行并将控制传递给处理程序。
所以,我的问题是-是否有可能不中断当前的执行,而是在一个分离的线程中处理TERM信号(?),以便我能够设置shutdown_flag = True,以便mainloop()有机会优雅地停止?
我找到的最简单的解决方法,从上面的回答中获得灵感是
class SignalHandler:
def __init__(self):
# register signal handlers
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
self.logger = Logger(level=ERROR)
def exit_gracefully(self, signum, frame):
self.logger.info('captured signal %d' % signum)
traceback.print_stack(frame)
###### do your resources clean up here! ####
raise(SystemExit)
根据前面的回答,我创建了一个上下文管理器,它可以保护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")