2015-10-14 123 views
0

我正在Debian上开发一个Python应用程序,当它从ether正常操作或可捕获信号调用关闭时,需要一些清理函数。下面是一些psudocode:防止Python3中信号处理的竞争条件

def exitHandler(sign, frame) 
    ... 
    variousCleanUp commands 
    ... 
    program ends here 

def main() 
    signal.signal(SIGINT, exitHandler) 
    signal.signal(SIGTERM, exitHandler) 

问题的,这是我所检测到关闭程序时,会导致两个SIGINT和SIGTERM发送。因此,exitHandler函数被调用两次,这不应该发生。

我能做些什么来防止这种情况发生?

回答

1

设置一个标志

execution = False 

def exitHandler(sign, frame): 
    global execution 
    if execution: 
     return 
    execution = True 
    ... # Rest of the code here 

,如果你有真正的并发性,使用threading.Lock

... 
lock_obj = threading.Lock() 
... 

def exitHandler(sign, frame): 
    with lock_obj: 
     ...