我已经看到了很多与此相关的问题......但我的代码适用于 python 2.6.2 并且无法在 python 2.6.5 上运行。我是否认为整个 atexit“当程序被信号杀死时不会调用通过此模块注册的函数”这件事不应该算在内,因为我正在捕捉信号然后干净地退出?这里发生了什么?这样做的正确方法是什么?
import atexit, sys, signal, time, threading
terminate = False
threads = []
def test_loop():
while True:
if terminate:
print('stopping thread')
break
else:
print('looping')
time.sleep(1)
@atexit.register
def shutdown():
global terminate
print('shutdown detected')
terminate = True
for thread in threads:
thread.join()
def close_handler(signum, frame):
print('caught signal')
sys.exit(0)
def run():
global threads
thread = threading.Thread(target=test_loop)
thread.start()
threads.append(thread)
while True:
time.sleep(2)
print('main')
signal.signal(signal.SIGINT, close_handler)
if __name__ == "__main__":
run()
蟒蛇2.6.2:
$ python halp.py
looping
looping
looping
main
looping
main
looping
looping
looping
main
looping
^Ccaught signal
shutdown detected
stopping thread
蟒蛇2.6.5:
$ python halp.py
looping
looping
looping
main
looping
looping
main
looping
looping
main
^Ccaught signal
looping
looping
looping
looping
...
looping
looping
Killed <- kill -9 process at this point
2.6.5 上的主线程似乎从不执行 atexit 函数。