如何优雅地处理SIGTERM信号? [英] How to process SIGTERM signal gracefully?
问题描述
假设我们有一个用python编写的琐碎的守护程序:
Let's assume we have such a trivial daemon written in python:
def mainloop():
while True:
# 1. do
# 2. some
# 3. important
# 4. job
# 5. sleep
mainloop()
,我们使用start-stop-daemon
对其进行守护进程,默认情况下,它会在--stop
上发送SIGTERM
(TERM
)信号.
and we daemonize it using start-stop-daemon
which by default sends SIGTERM
(TERM
) signal on --stop
.
让我们假设当前执行的步骤是#2
.此时此刻,我们正在发送TERM
信号.
Let's suppose the current step performed is #2
. And at this very moment we're sending TERM
signal.
发生的事情是执行立即终止.
What happens is that the execution terminates immediately.
我发现我可以使用signal.signal(signal.SIGTERM, handler)
处理信号事件,但事实是它仍然会中断当前执行并将控制权传递给handler
.
I've found that I can handle the signal event using signal.signal(signal.SIGTERM, handler)
but the thing is that it still interrupts the current execution and passes the control to handler
.
所以,我的问题是-是否可以不中断当前执行,而是在单独的线程(?)中处理TERM
信号,以便我能够设置shutdown_flag = True
以便使mainloop()
有机会优雅地停下来?
So, my question is - is it possible to not interrupt the current execution but handle the TERM
signal in a separated thread (?) so that I was able to set shutdown_flag = True
so that mainloop()
had a chance to stop gracefully?
推荐答案
基于类的全新使用解决方案:
A class based clean to use solution:
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 not killer.kill_now:
time.sleep(1)
print("doing something in a loop ...")
print("End of the program. I was killed gracefully :)")
这篇关于如何优雅地处理SIGTERM信号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!