From here, i found that when a signal is received, exit_gracefully
is called meanwhile the code inside while True
is running. At first i thought that handler is running in another thread so i wrote a code to test it out:
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')
I ran the code and first sent a SIGTERM
signal (using kill -SIGTERM pid
command) and then sent a SIGINT
signal. The output was:
main execution PID: 1002
current thread identity: 140284238558976
Hello
Hello
handler PID: 1002
current thread identity: 140284238558976
Hello
Hello
Good bye
You see that everything is the same, but how it's possible that the handler is running in the same exact context that main code is executing? Shouldn't be in another thread?