What are the rules surrounding Python threads and how Unix signals are handled?
Is KeyboardInterrupt
, which is triggered by SIGINT
but handled internally by the Python runtime, handled differently?
What Is Signaling In Python? In simplistic terms, a signal is an event. A signal is used to interrupt the execution of a running function. The signals are always executed in the main Python thread. An event is generated to notify other parts of an application.
Signals are software interrupts sent to a program to indicate that an important event has occurred. The events can vary from user requests to illegal memory access errors. Some signals, such as the interrupt signal, indicate that a user has asked the program to do something that is not in the usual flow of control.
There are six signals that can be delivered as a consequence of a hardware exception: SIGBUS, SIGEMT, SIGFPE, SIGILL, SIGSEGV, and SIGTRAP.
First, when setting up signal handlers using the signal
module, you must create them in the main thread. You will receive an exception if you try to create them in a separate thread.
Signal handlers registered via the signal.signal()
function will always be called in the main thread. On architectures which support sending signals to threads, at the C level I believe the Python runtime ignores all signals on threads and has a signal handler on the main thread, which it uses to dispatch to your Python-code signal handler.
The documentation for the thread
module states that the KeyboardInterrupt
exception (which is ordinarily triggered by SIGINT
) can be delivered to an arbitrary thread unless you have the signal
module available to you, which all Unix systems should have. In that case, it's delivered to the main thread. If you're on a system without signal
, you'll have to catch KeyboardInterrupt
in your thread and call thread.interrupt_main()
to re-raise it in the main thread.
More information can be found in the Python docs for the thread
and signal
modules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With