我正在开发的应用程序中的一个模块旨在用作Linux上的长时间运行进程,我希望它可以优雅地处理SIGTERM,SIGHUP和其他可能的信号。该程序的核心部分实际上是一个循环,它定期运行一个函数(反过来唤醒另一个线程,但这不太重要)。看起来或多或少是这样的:
while True:
try:
do_something()
sleep(60)
except KeyboardInterrupt:
break
cleanup_and_exit()
我现在要添加的是捕获SIGTERM并退出循环,就像KeyboardInterrupt
异常一样。
我有一个想法是添加一个标志,该标志将由信号处理函数设置为True,并用睡眠(0.1)或其他任何东西替换sleep(60),并使用一个计算秒数的计数器:
_exit_flag = False
while not _exit_flag:
try:
for _ in xrange(600):
if _exit_flag: break
do_something()
sleep(0.1)
except KeyboardInterrupt:
break
cleanup_and_exit()
以及其他地方:
def signal_handler(sig, frame):
_exit_flag = True
但我不确定这是最好/最有效的方法。
答案 0 :(得分:1)
为什么不将清理推送到处理程序中,而不是在主循环中使用sentinel,因此必须比你真正想检查它更频繁地唤醒?类似的东西:
class BlockingAction(object):
def __new__(cls, action):
if isinstance(action, BlockingAction):
return action
else:
new_action = super(BlockingAction, cls).__new__(cls)
new_action.action = action
new_action.active = False
return new_action
def __call__(self, *args, **kwargs):
self.active = True
result = self.action(*args, **kwargs)
self.active = False
return result
class SignalHandler(object):
def __new__(cls, sig, action):
if isinstance(action, SignalHandler):
handler = action
else:
handler = super(SignalHandler, cls).__new__(cls)
handler.action = action
handler.blocking_actions = []
signal.signal(sig, handler)
return handler
def __call__(self, signum, frame):
while any(a.active for a in self.blocking_actions):
time.sleep(.01)
return self.action()
def blocks_on(self, action):
blocking_action = BlockingAction(action)
self.blocking_actions.append(blocking_action)
return blocking_action
def handles(signal):
def get_handler(action):
return SignalHandler(signal, action)
return get_handler
@handles(signal.SIGTERM)
@handles(signal.SIGHUP)
@handles(signal.SIGINT)
def cleanup_and_exit():
# Note that this assumes that this method actually exits the program explicitly
# If it does not, you'll need some form of sentinel for the while loop
pass
@cleanup_and_exit.blocks_on
def do_something():
pass
while True:
do_something()
time.sleep(60)