让我们假设我们有一个用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(signal.SIGTERM, handler)
处理信号事件,但事实是它仍然会中断当前执行并将控制传递给handler
。
所以,我的问题是 - 是否可以不中断当前执行但是在一个单独的线程(?)中处理TERM
信号,这样我才能设置shutdown_flag = True
以便{{} 1}}有机会优雅地停止吗?
答案 0 :(得分:219)
基于类的清洁使用解决方案:
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 :)"
答案 1 :(得分:44)
首先,我不确定您是否需要第二个线程来设置shutdown_flag。为什么不直接在SIGTERM处理程序中设置它?
另一种方法是从SIGTERM
处理程序引发异常,该处理程序将在堆栈中向上传播。假设你有适当的异常处理(例如with
/ contextmanager
和try: ... 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"
:
$ ./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
现在看一下Ctrl-C行为:
SIGTERM
这次我使用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
:
{{1}}
答案 2 :(得分:27)
我认为你接近可能的解决方案。
在单独的线程中执行mainloop
并使用属性shutdown_flag
扩展它。可以在主线程中使用signal.signal(signal.SIGTERM, handler)
捕获信号(而不是在单独的线程中)。信号处理程序应将shutdown_flag
设置为True并等待线程以thread.join()
答案 3 :(得分:21)
这是一个没有线程或类的简单示例。
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
答案 4 :(得分:10)
基于之前的答案,我创建了一个上下文管理器,可以防止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")
答案 5 :(得分:1)
我如何使用信号的代码示例。
#!/usr/bin/env python
import signal
def ctrl_handler(signum, frm) :
print " You can't cannot kill me"
print "Installing signal handler..."
signal.signal(signal.SIGINT, ctrl_handler)
print "done"
while True :
#do somthing
pass
答案 6 :(得分:0)
为我找到了最简单的方法。 在这里,为了清楚起见,有一个使用fork的示例,这种方式对流量控制很有用。
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)
答案 7 :(得分:0)
我发现的最简单的解决方案是,通过以上回答获得灵感
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)