I'm trying to catch SIGINT (or keyboard interrupt) in Python 2.7 program. This is how my Python test script
./test & pid=$!
kill -s 2 $pid
Python installs a small number of signal handlers by default: SIGPIPE ... and SIGINT is translated into a KeyboardInterrupt exception
There is one case in which the default sigint handler is not installed at startup, and that is when the signal mask contains
SIGINT at program startup. The code responsible for this can be found here.
The signal mask for ignored signals is inherited from the parent process, while handled signals are reset to
SIG_DFL. So in case
SIGINT was ignored the condition
if (Handlers[SIGINT].func == DefaultHandler) in the source won't trigger and the default handler is not installed, python doesn't override the settings made by the parent process in this case.
So let's try to show the used signal handler in different situations:
# invocation from interactive shell $ python -c "import signal; print(signal.getsignal(signal.SIGINT))" <built-in function default_int_handler> # background job in interactive shell $ python -c "import signal; print(signal.getsignal(signal.SIGINT))" & <built-in function default_int_handler> # invocation in non interactive shell $ sh -c 'python -c "import signal; print(signal.getsignal(signal.SIGINT))"' <built-in function default_int_handler> # background job in non-interactive shell $ sh -c 'python -c "import signal; print(signal.getsignal(signal.SIGINT))" &' 1
So in the last example,
SIGINT is set to 1 (
SIG_IGN). This is the same as when you start a background job in a shell script, as those are non interactive by default (unless you use the
-i option in the shebang).
So this is caused by the shell ignoring the signal when launching a background job in a non interactive shell session, not by python directly. At least
dash behave this way, I've not tried other shells.
There are two options to deal with this situation:
manually install the default signal handler:
import signal signal.signal(signal.SIGINT, signal.default_int_handler)
-i option to the shebang of the shell script, e.g:
edit: this behaviour is documented in the bash manual:
When job control is not in effect, asynchronous commands ignore SIGINT and SIGQUIT in addition to these inherited handlers.
which applies to non-interactive shells as they have job control disabled by default, and is actually specified in POSIX: Shell Command Language