Skip to content

Signals: how a process is asked to stop

Working knowledgeConcept

You press Ctrl-C, run kill, or deploy a new version and the old container stops. Each time, the process receives a signal. Here is what a signal is, what a process can do with one, and how to shut down without losing the work in progress.

01 A signal is a number the kernel delivers

A signal is a small notification sent to a process. It carries almost nothing: just a number, such as 15. It can come from another process through the kill() system call, from the terminal when you press a key, or from the kernel itself, for example when the program touches memory it does not own.

Signals you will meet (numbers are for Linux on x86 and Arm)
SignalNo.Usually sent byDefault action
SIGINT2Ctrl-C in the terminalterminate
SIGTERM15kill, docker stop, Kubernetes, systemdterminate
SIGKILL9kill -9, the OOM killer, the end of a grace periodterminate; cannot be caught
SIGHUP1the terminal closing; by convention, “reload your config”terminate
SIGQUIT3Ctrl-\ in the terminalterminate and dump core
SIGSTOP / SIGTSTP19 / 20a debugger / Ctrl-Zpause; SIGSTOP cannot be caught
SIGCHLD17the kernel, when a child process exitsignore
SIGSEGV11the kernel, on a bad memory accessterminate and dump core
SIGPIPE13the kernel, on writing to a pipe nobody readsterminate

The kernel never interrupts a process in the middle of an instruction to hand it a signal. It sets a pending bit for that signal and acts on it when the process next returns from the kernel to its own code, which happens constantly: after every system call and every timer tick. Ordinary signals do not queue: two SIGTERMs that arrive before the first is handled count as one.

02 Three ways a process can respond

For each signal, a process has an action recorded in the kernel. It starts as the default, and the program can change it with sigaction() (or signal.signal() in Python, process.on() in Node).

DefaultKernel decidesFor SIGTERM and SIGINT that means the process dies at once, with no cleanup in your code.
IgnoreNothing happensThe signal is thrown away. Python ignores SIGPIPE this way and reports a broken pipe as an exception instead.
HandleYour function runsThe kernel diverts the process into your handler, then lets it carry on where it was.

SIGKILL and SIGSTOP cannot be handled, blocked or ignored. That is the point of them: they always work. It also means that after SIGKILL nothing of yours runs: no handler, no finally, no flushing of buffers, no deleting of lock files.

03 A graceful stop, step by step

A worker that takes jobs from a queue should finish the job it is on, take no new one, and exit. The handler does not do the shutdown itself. It only sets a flag, and the main loop checks the flag between jobs.

worker.py
import signal
import sys
import time
stopping = False
def on_stop(signum, frame):
global stopping
print(f"got {signal.Signals(signum).name}, finishing the current job", flush=True)
stopping = True
signal.signal(signal.SIGTERM, on_stop)
signal.signal(signal.SIGINT, on_stop)
job = 0
while not stopping:
A graceful stop with a SIGTERM handler
Step 1 of 6
Who tells whom
DockerKernelworker.pyNothing sent yet
Inside the worker process
Value
Pending signalsnone
SIGTERM actionrun on_stop()
stoppingFalse
Current jobjob 2 running
  • just sent
  • just changed
  • finished cleanly

worker.py is PID 1 in a container, halfway through job 2. At start-up it registered on_stop() as its SIGTERM handler, so the kernel has that recorded for the process.

Try it. This is a real run on macOS; Linux prints the same.

Shell
python3 worker.py & # start it in the background
sleep 3
kill $! # SIGTERM to the last background job
wait $!; echo "exit status $?"
Text
job 1 started
job 1 done
job 2 started
got SIGTERM, finishing the current job
job 2 done
clean exit
exit status 0

Swap kill $! for kill -9 $! and the handler never runs. On Linux, bash reports it like this (a real run in a container; the PID will differ):

Text
job 1 started
job 1 done
job 2 started
bash: line 1: 7 Killed python3 worker.py
exit status 137

Why only a flag? A handler can run between any two steps of your program, perhaps while it holds a lock or is half-way through updating a data structure. In C, only a short list of async-signal-safe functions (such as write()) may be called from a handler; printf() and malloc() are not on it. CPython is gentler: its C handler only notes the signal, and your Python handler runs later in the main thread between bytecodes. Keeping handlers to “set a flag” is safe everywhere.

04 SIGTERM first, SIGKILL after a grace period

Everything that stops processes for you follows the same two-step pattern: ask politely with SIGTERM, wait a while, then force it with SIGKILL. The wait is your budget for a clean shutdown.

Default grace periods
ToolSends firstWaitsSetting
docker stopSIGTERM (or the image’s STOPSIGNAL)10 sdocker stop -t
KubernetesSIGTERM, after any preStop hook30 sterminationGracePeriodSeconds
systemdSIGTERM (KillSignal=)90 sTimeoutStopSec

The trap is a program with no handler running as PID 1, which is what your app usually is inside a container. The kernel shields each PID namespace’s first process from signals it has not set a handler for, so the default “terminate” never happens.

No handler: SIGTERM ignored, then SIGKILL
Step 1 of 6
Who tells whom
DockerKernelworker.pyNothing sent yet
Inside the worker process
Value
Pending signalsnone
SIGTERM actiondefault
stopping–
Current jobjob 4 running
  • just sent
  • dropped or cut off
  • still running

This time the program installed no SIGTERM handler, so its action is the default. It is PID 1 in its container, which matters in a moment.

A real run with a handler-less Python loop as the container’s main process. The stop takes the full grace period, and the exit code says it was killed:

Shell
# plain.py is a loop with no signal handler: while True: time.sleep(1)
docker run -d --name plain -v "$PWD":/w python:3.12-slim python /w/plain.py
time docker stop -t 10 plain
docker inspect -f '{{.State.ExitCode}}' plain
Text
plain
real 0m10.146s
user 0m0.016s
sys 0m0.012s
137

Two fixes: install a SIGTERM handler, or run a tiny init in front of your app (docker run --init, or tini in the image) that is PID 1 instead, passes signals on and reaps exited children. With worker.py from above, the same docker stop returns as soon as the current job ends.

05 Send and inspect signals yourself

Shell
kill -l # list signal names and numbers
kill -TERM 4242 # same as plain `kill 4242`
kill -9 4242 # SIGKILL: last resort
kill -0 4242 && echo alive # signal 0 sends nothing, only checks the PID exists
# which signals a process catches (Linux): a bit mask, bit n-1 for signal n
grep -E 'SigCgt|SigIgn' /proc/4242/status
# a shell script can handle signals too
trap 'echo stopping; exit 0' TERM INT

Here is /proc/1/status for worker.py running as PID 1 in a container, from a real run. SigCgt is the set of caught signals: 0x4002 has bits 1 and 14 set, so signals 2 (SIGINT) and 15 (SIGTERM) have handlers. SigIgn shows signals 13 (SIGPIPE) and 25 (SIGXFSZ), which CPython ignores at start-up.

Text
SigIgn: 0000000001001000
SigCgt: 0000000000004002

Keys in the terminal send signals to the whole foreground process group, not one process: Ctrl-C sends SIGINT to every process in a pipeline such as cat log | grep x.

06 When it bites

CMD python app.pyA shell in the middleThe shell form of CMD runs your app through /bin/sh -c. Depending on the shell, sh may stay as PID 1 and not pass SIGTERM on. Use the exec form, CMD ["python", "app.py"], or exec in an entry script.
SIGTERM → exit at onceStopping before traffic moves awayIn Kubernetes, removing a pod from the Service and sending SIGTERM happen at about the same time. A server that quits instantly drops requests still being routed to it. Keep serving for a few seconds, for example with a preStop sleep, then drain.
grace 10 s, drain 30 sA shutdown longer than the grace periodIf finishing in-flight work takes longer than the grace period, SIGKILL arrives anyway. Raise the period or cut the work into shorter pieces.
kill -9 firstReaching for SIGKILL firstIt skips every cleanup: temporary files stay, lock files stay, buffered log lines are lost, a database client never says goodbye. Send SIGTERM and wait first.
print | head -1SIGPIPE ends a pipelineWhen head exits, the writer gets SIGPIPE on its next write and, by default, dies quietly. Usually that is what you want; in a server writing to a closed socket it is not, so servers ignore SIGPIPE and handle the write error.

07 Check yourself

Question

A container’s main process is a Python script with no signal handlers. You run docker stop. What happens?

Question

Your SIGTERM handler closes the database pool, flushes logs and uploads a report, taking 40 seconds. It runs in Kubernetes with default settings. What goes wrong?

Question

Why should a signal handler usually just set a flag?

08 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?