Section 15.28

signal module

Definition

The signal module is the module of the Python §12.23 standard library for handling signals. A signal is a short notification that the operating system can deliver to a process at any moment, such as SIGINT when the user presses Ctrl+C. The module lets a program install a Python function as a signal’s handler. In CPython, the standard implementation of Python, written in C, a small C-level handler records the signal on arrival; the Python handler runs later, in the main thread, when the interpreter §2.13 next checks that record.

The idea

A Python service must save its state and exit cleanly when the system asks it to stop. The system asks by sending SIGTERM, the termination signal, and the service installs a handler that sets a stop flag. The programmer expects the handler to run the moment the signal arrives. It may not. If the main thread is running native code at that moment, meaning machine code compiled from C or a similar language, such as a numerical library, the Python handler waits until that code returns to the interpreter.

The reason is safety. A signal can arrive between any two machine instructions, even while the interpreter is halfway through updating its own data structures, and Python code run at that instant would find them half changed. So CPython splits the work in two. The C-level handler does only what is safe at any instant: it records that the signal arrived. The interpreter looks at that record at safe points while it runs bytecode §2.4, the compact instructions into which CPython compiles Python source, and only then calls the Python handler. A doorbell is a fair picture: it can ring at any moment, but the door is opened only when the person inside can put down what they are doing. The picture stops in one respect: while native code runs, the interpreter does not hear the bell at all, unless that code itself checks.

How it works

Installing a handler. signal.signal(signum, handler) installs handler for the signal numbered signum. The handler is a Python function that receives the signal number and the stack frame, the interpreter’s record of the function call that was running. Instead of a function, the handler can be signal.SIG_IGN, which ignores the signal, or signal.SIG_DFL, which restores the operating system’s default action; for SIGTERM the default action ends the process. Only the main thread of the main interpreter may install a handler; a call from another thread raises ValueError. By default CPython turns SIGINT into the exception KeyboardInterrupt.

What happens when a signal arrives.

  1. The kernel, the core of the operating system, stops one thread of the process where it is and runs CPython’s C-level handler in that thread.

  2. The C-level handler records which signal arrived, sets a flag that tells the interpreter a signal is pending, and returns. If the program registered a file descriptor §15.21 with signal.set_wakeup_fd, the handler also writes the signal number to it as one byte, which wakes an event loop §14.23 that waits for input.

  3. If the signal cut short a system call in the main thread, meaning a request to the kernel such as a read or a sleep, that call returns early to the interpreter.

  4. The main thread’s interpreter loop checks the pending flag at frequent points while it runs bytecode. On seeing the flag, it calls the Python handler of each recorded signal.

  5. If the handler raises an exception, the exception appears in the main thread where the check happened. If the handler returns normally, Python retries any system call cut short in step 3, with any timeout §9.34 reduced by the time already spent, as Python Enhancement Proposal (PEP) 475 specifies for Python 3.5 and later.

Where the delay comes from. While the main thread runs native code, the interpreter loop is not running in that thread, so nothing looks at the pending flag. The Python handler waits until the native code returns, or until the native code itself calls the C function PyErr_CheckSignals, which runs pending handlers. Some native functions call it during long computations and others never do, so the delay depends on the function.

One thread only. Python handlers always run in the main thread, even when the signal arrived while another thread was running, so signals cannot carry a message to a particular thread.

Worked example

A service’s main thread calls a native function ff at time 0 s. The function runs for 4.0 s without returning and without calling PyErr_CheckSignals. The service’s handler for SIGTERM sets stop_requested = True, and the main loop checks stop_requested after each call to ff. A supervisor, the program that started the service, allows 2.0 s for a clean exit.

  1. At 1.0 s the supervisor sends SIGTERM. The C-level handler runs at once and records the signal.

  2. From 1.0 s on, ff keeps running, and no Python code runs in the main thread.

  3. At 1.0+2.0=3.01.0 + 2.0 = 3.0 s the grace period §9.21 ends. The supervisor sends SIGKILL, the kill signal, which no handler can catch, block or ignore, and the kernel ends the process.

The Python handler never ran, and the state was not saved. Without the deadline, the handler would have run at 4.0 s, when ff returned: 4.0−1.0=3.04.0 - 1.0 = 3.0 s after the signal, which exceeds the grace period by 3.0−2.0=1.03.0 - 2.0 = 1.0 s.

Two designs respect the 2.0 s budget. In the first, the service runs ff in pieces that each take at most 1.0 s and checks stop_requested between pieces. The handler then runs at most 1.0 s after the signal, which leaves at least 2.0−1.0=1.02.0 - 1.0 = 1.0 s to save the state. In the second, used when ff cannot be divided, the service accepts that it may be killed at any point and makes every save of its state safe to stop part-way, for example by writing a new file and then renaming it over the old one.

Stated precisely

Let tst_{s} be the time at which the operating system delivers a signal ss to the process. Let tct_{c} be the first time after tst_{s} at which the main thread of the main interpreter checks for pending signals, either in its bytecode loop or through a call to PyErr_CheckSignals. CPython’s contract is the following.

  1. The C-level handler runs at tst_{s} and only records the signal.

  2. The Python handler for ss runs in the main thread when that thread reaches tct_{c}, and never in another thread.

  3. Python sets no upper bound on the delay tc−tst_{c} - t_{s}. The delay is at least the remaining run time of any native call that the main thread is making at tst_{s} and that does not check for signals.

  4. If ss arrives more than once before tct_{c}, the handler may run only once, because the record is a flag, not a count.

  5. SIGKILL and SIGSTOP, the signal that pauses a process, cannot be caught, so no handler ever runs for them.

A time bound on a shutdown driven by a handler needs three further assumptions, none of which installing the handler provides: the main thread reaches a check within a known time after any signal; the handler finishes within a known time; and the code that reads the stop flag reads it within a known time. A bound that must hold whatever the code is doing has to be enforced from outside the process, for example by a supervisor that sends SIGKILL after a deadline.

Limits and common mistakes

A handler that sets a flag requests cancellation §9.29; it does not carry it out. Native calls, other threads, child processes and outside devices keep going until they check the flag or are stopped by other means, and the program has stopped only when each of them is known to have ended.

Faults caused by the running code cannot be handled in Python. SIGSEGV, the segmentation-violation signal for an invalid memory access, and SIGFPE, the arithmetic-error signal, sent for example on an integer division by zero in C on an x86 processor, are raised by the very instruction that was running. When the C-level handler returns, that instruction runs again and faults again, so a Python handler for such a signal leaves the program apparently hung. The faulthandler module is the tool for these signals: it prints the list of active Python function calls before the process dies.

A Python handler can run between any two bytecode instructions of the main thread, for example while a lock is held or in the middle of a write to a file. A handler that takes a lock the interrupted code already holds waits forever, a deadlock §9.14. A handler that writes to the same buffered file can raise RuntimeError, because the file object does not support reentrancy §9.27, a second call starting before the first has returned. Keep handlers short: set a flag or an event. For the same reason, KeyboardInterrupt can appear at any point and leave data half updated.

Platforms differ. On Windows, signal.signal accepts only SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM and SIGBREAK, and the module’s alarm and timer functions are not available.

A timeout built on signal.alarm, which sends SIGALRM, the alarm signal, after a given number of seconds, has the same weakness: the handler that raises the timeout exception waits for native code like any other handler.

Even SIGKILL takes effect only when the process can be stopped. A process waiting inside the kernel in an uninterruptible wait, typically for a disk or a network file system, ends only when that wait ends.

Questions answered

Can a long-running native operation delay delivery of a Python-level handler?

Yes, a long-running native operation can delay a Python-level signal handler, and in general without any upper bound. In CPython, the standard implementation of Python, the operating system delivers a signal at once, but only to a small handler written in C that records it; the Python-level handler runs later, in the main thread, when the interpreter next checks for recorded signals. While the main thread is inside a native operation, meaning machine code compiled from C or a similar language, the interpreter makes no such check unless that code calls the C function PyErr_CheckSignals. A native call that starts at 0 s and returns at 4 s, with SIGTERM, the termination signal, arriving at 1 s, therefore delays the Python handler by 4−1=34 - 1 = 3 s.

Installing a handler thus guarantees no shutdown time. A hard time bound needs enforcement from outside the process, for example a supervisor that sends SIGKILL, which no handler can intercept, after a grace period.

Related entries: Timeout versus cancellation (§13.25), Process closure (§13.23), subprocess (§12.40), Asynchronous completion (§9.28), Reentrancy (§9.27), Cancellation (§9.29), Interrupt (§6.11). Further reading: [51].