[英]Implementing signal handling on a sleep loop
我正在開發的應用程序中的一個模塊旨在用作Linux上長時間運行的進程,我希望它能夠優雅地處理SIGTERM,SIGHUP和其他信號。 該程序的核心部分實際上是一個循環,該循環定期運行一個函數(依次喚醒另一個線程,但這並不重要)。 看起來或多或少是這樣的:
while True:
try:
do_something()
sleep(60)
except KeyboardInterrupt:
break
cleanup_and_exit()
我現在要添加的是捕獲SIGTERM並退出循環,就像KeyboardInterrupt
異常一樣。
我想到的一個想法是添加一個將由信號處理程序函數設置為True的標志,並用計數秒的計數器將sleep(60)替換為sleep(0.1)或其他內容:
_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
但是我不確定這是最好/最有效的方法。
與其在主循環中使用哨兵,而不必比您真正想要檢查的次數更頻繁地喚醒,為什么不將清理推入處理程序? 就像是:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.