0

我正在开发的应用程序中的一个模块旨在用作 Linux 上的长时间运行进程,我希望它能够优雅地处理 SIGTERM、SIGHUP 和可能的其他信号。程序的核心部分实际上是一个循环,它周期性地运行一个函数(这反过来又唤醒另一个线程,但这并不重要)。它或多或少看起来像这样:

while True: 
    try:
        do_something()
        sleep(60)
    except KeyboardInterrupt:
        break

cleanup_and_exit()

我现在要添加的是捕获 SIGTERM 并退出循环,就像KeyboardInterrupt异常一样。

我的一个想法是添加一个标志,该标志将由信号处理函数设置为 True ,并用 sleep(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

但我不确定这是最好/最有效的方法。

4

1 回答 1

1

与其在主循环中使用哨兵,因此不得不比您真正想要检查的更频繁地唤醒,为什么不将清理推送到处理程序中呢?就像是:

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)
于 2013-01-02T16:36:13.000 回答