Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the Python thread + Unix signals semantics?

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?

like image 247
Joe Shaw Avatar asked Jul 27 '09 16:07

Joe Shaw


People also ask

What are Python signals?

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.

What are signals in Unix programming?

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.

How many UNIX signals are there?

There are six signals that can be delivered as a consequence of a hardware exception: SIGBUS, SIGEMT, SIGFPE, SIGILL, SIGSEGV, and SIGTRAP.


1 Answers

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.

like image 77
Joe Shaw Avatar answered Sep 23 '22 13:09

Joe Shaw