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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First, when setting up signal handlers using the
signalmodule, 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
threadmodule states that theKeyboardInterruptexception (which is ordinarily triggered bySIGINT) can be delivered to an arbitrary thread unless you have thesignalmodule 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 withoutsignal, you’ll have to catchKeyboardInterruptin your thread and callthread.interrupt_main()to re-raise it in the main thread.More information can be found in the Python docs for the
threadandsignalmodules.