我从这里了解到,当接收到信号时,exit_gracefully
被调用,同时while True
内部的代码也在运行。起初我以为处理程序在另一个线程中运行,所以我编写了一段代码来测试它:
import os
import signal
import threading
def sig_handler(signal_frame, num):
print('handler PID: {}'.format(os.getpid()))
print('current thread identity: {}'.format(threading.current_thread().ident))
signal.signal(signal.SIGTERM, sig_handler)
try:
print('main execution PID: {}'.format(os.getpid()))
print('current thread identity: {}'.format(threading.current_thread().ident))
while True:
time.sleep(5)
print('Hello')
except KeyboardInterrupt:
print('Good bye')
我运行了这段代码,首先发送了一个 SIGTERM
信号(使用 kill -SIGTERM pid
命令),然后发送了一个 SIGINT
信号。输出结果为:
main execution PID: 1002
current thread identity: 140284238558976
Hello
Hello
handler PID: 1002
current thread identity: 140284238558976
Hello
Hello
Good bye
您看到的一切都一样,但处理程序如何在与主代码完全相同的上下文中运行?它不应该在另一个线程中吗?