Signals and graceful shutdown
suggest changeA signal is a small asynchronous notification the operating system delivers to a process. You send one when you press Ctrl+C in a terminal, run kill <pid>, stop a Docker container or let systemd restart a service. If the program doesn't handle the signal, the default action usually kills it on the spot: open files are not flushed, temporary files are left behind and half-finished work is lost.
Graceful shutdown means catching the "please stop" signals and turning them into an orderly exit: finish or abandon the current unit of work, stop worker threads and child processes, release resources and exit with a meaningful status code.
The signal module is the Python interface to signals. The ones you'll meet most often:
| Signal | Number (Linux) | Sent by | Default action |
|---|---|---|---|
SIGINT |
2 | Ctrl+C in a terminal | Python raises KeyboardInterrupt |
SIGTERM |
15 | kill <pid>, docker stop, systemd, Kubernetes |
terminate |
SIGHUP |
1 | terminal closed; by convention "reload config" for daemons | terminate |
SIGKILL |
9 | kill -9 <pid>, OOM killer |
terminate, cannot be caught |
SIGUSR1, SIGUSR2 |
10, 12 | user-defined | terminate |
SIGALRM |
14 | signal.alarm(), signal.setitimer() |
terminate |
Most of this article is about Unix (Linux, macOS). Windows supports only a few signals; see the section on Windows near the end. The Unix examples were run with Python 3.14 on Linux, and the Windows ones with Python 3.13.
Signal names and current handlers
Signals are members of the signal.Signals enum. signal.getsignal() returns the handler currently installed for a signal:
import signal
for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP, signal.SIGKILL, signal.SIGUSR1):
print(f"{sig.name:8} {sig.value:2} {signal.strsignal(sig)}")
print(signal.getsignal(signal.SIGINT))
print(repr(signal.getsignal(signal.SIGTERM)))
SIGINT 2 Interrupt
SIGTERM 15 Terminated
SIGHUP 1 Hangup
SIGKILL 9 Killed
SIGUSR1 10 User defined signal 1
<built-in function default_int_handler>
<Handlers.SIG_DFL: 0>
At startup Python installs only one handler of its own: default_int_handler for SIGINT, which raises KeyboardInterrupt. Every other signal keeps the operating system default, SIG_DFL.
What happens without a handler
This matters because the two most common shutdown signals behave very differently by default. The parent below starts a child that sleeps inside try/finally, then sends it SIGINT and SIGTERM:
import signal
import subprocess
import sys
import time
child_code = """
import time
try:
print("child: working", flush=True)
time.sleep(10)
finally:
print("child: cleanup ran", flush=True)
"""
for name in ("SIGINT", "SIGTERM"):
p = subprocess.Popen([sys.executable, "-c", child_code])
time.sleep(0.5)
p.send_signal(getattr(signal, name))
p.wait()
print(f"after {name}: returncode={p.returncode}\n")
child: working
child: cleanup ran
Traceback (most recent call last):
File "<string>", line 5, in <module>
time.sleep(10)
~~~~~~~~~~^^^^
KeyboardInterrupt
after SIGINT: returncode=-2
child: working
after SIGTERM: returncode=-15
SIGINT becomes a KeyboardInterrupt exception, so finally blocks, with statements and atexit handlers run. SIGTERM kills the process immediately: no finally, no atexit, no buffered output flushed. That's what happens to an unprepared Python service every time it's deployed or its container is stopped.
A negative returncode from subprocess means "killed by signal N". A shell reports the same thing as exit status 128 + N, e.g. 143 for SIGTERM and 130 for SIGINT. Since Python 3.8, an uncaught KeyboardInterrupt makes the interpreter exit by re-raising SIGINT on itself, so the parent sees a proper "killed by SIGINT" status rather than exit code 1.
Installing a handler
signal.signal(signum, handler) installs a function that is called with two arguments: the signal number and the stack frame that was executing when the signal arrived. It returns the previous handler.
import os
import signal
import time
def handler(signum, frame):
name = signal.Signals(signum).name
print(f"got {name} while in {frame.f_code.co_name}()")
signal.signal(signal.SIGUSR1, handler)
signal.signal(signal.SIGTERM, handler)
def work():
os.kill(os.getpid(), signal.SIGUSR1)
signal.raise_signal(signal.SIGTERM)
time.sleep(0.1)
print("still running")
work()
got SIGUSR1 while in work()
got SIGTERM while in work()
still running
os.kill(pid, sig) sends a signal to any process you have permission to signal; signal.raise_signal(sig) sends one to the current process. Both are handy for testing handlers.
Important rules about Python signal handlers:
- Handlers always run in the main thread of the main interpreter, no matter which thread was running when the signal arrived. You can also only install handlers from the main thread.
- Handlers don't run immediately. The C-level handler just sets a flag; the interpreter calls your Python function at the next bytecode boundary in the main thread. A long-running C call (a big regex match, a C extension doing heavy work) delays the handler until it returns.
- Blocking calls such as
time.sleep(),socket.recv()orEvent.wait()are interrupted so the handler can run. If the handler returns normally, the call is automatically resumed (PEP 475). If the handler raises, the exception propagates out of the blocking call. SIGKILLandSIGSTOPcan't be caught, blocked or ignored.
Trying to install a handler from another thread fails:
import signal
import threading
def handler(signum, frame):
pass
def install():
try:
signal.signal(signal.SIGTERM, handler)
except ValueError as e:
print("ValueError:", e)
t = threading.Thread(target=install)
t.start()
t.join()
ValueError: signal only works in main thread of the main interpreter
Pattern 1: turn SIGTERM into an exception
The simplest fix for the SIGTERM problem is to make it behave like SIGINT: raise an exception from the handler. sys.exit() raises SystemExit, which unwinds the stack and runs every finally, with exit and atexit callback:
import atexit
import os
import signal
import sys
import time
def on_sigterm(signum, frame):
print(f"received {signal.Signals(signum).name}, exiting")
sys.exit(128 + signum)
signal.signal(signal.SIGTERM, on_sigterm)
atexit.register(lambda: print("atexit: flushed state"))
try:
with open("data.tmp", "w") as f:
f.write("partial")
os.kill(os.getpid(), signal.SIGTERM) # simulate `kill <pid>`
time.sleep(10)
finally:
os.remove("data.tmp")
print("finally: removed data.tmp")
received SIGTERM, exiting
finally: removed data.tmp
atexit: flushed state
The process exits with status 143 (128 + 15), the conventional status for "terminated by SIGTERM".
This is a good default for scripts and command-line tools. Its weakness is that the exception can be raised at any bytecode in the main thread, including in the middle of a multi-step update that you never expected to be interrupted. For long-running services, the next pattern is safer.
Pattern 2: set a flag and stop at a safe point
Instead of interrupting the code, the handler only records that shutdown was requested. The main loop checks the flag between units of work, so a job is never cut in half. A threading.Event works well as the flag because Event.wait(timeout) doubles as a sleep that ends early when shutdown is requested:
import os
import signal
import threading
import time
stop = threading.Event()
def request_stop(signum, frame):
print(f"{signal.Signals(signum).name}: finishing current job, then stopping")
stop.set()
signal.signal(signal.SIGTERM, request_stop)
signal.signal(signal.SIGINT, request_stop)
# simulate `kill <pid>` arriving 1.2 seconds from now
threading.Timer(1.2, os.kill, (os.getpid(), signal.SIGTERM)).start()
job = 0
while not stop.is_set():
job += 1
print(f"job {job}: start")
time.sleep(0.5) # a unit of work that must not be cut in half
print(f"job {job}: done")
stop.wait(timeout=0.3) # interruptible pause between jobs
print("clean shutdown")
job 1: start
job 1: done
job 2: start
SIGTERM: finishing current job, then stopping
job 2: done
clean shutdown
The signal arrived during job 2, the handler ran, time.sleep() resumed, job 2 completed, and the loop ended. Keep handlers this small: setting a flag is safe, while doing real work in a handler (logging through locks, I/O, acquiring locks your main code also holds) can deadlock or corrupt state, because the handler interrupts whatever the main thread was doing.
Stopping worker threads
Only the main thread receives signals, and Python has no way to forcibly stop a thread. So the main thread catches the signal and tells the workers to stop through a shared Event, then waits for them with join():
import os
import signal
import sys
import threading
import time
stop = threading.Event()
def worker(n):
while not stop.is_set():
time.sleep(0.2) # do some work
print(f"worker {n}: saving progress and exiting")
def on_signal(signum, frame):
print(f"main thread got {signal.Signals(signum).name}")
stop.set()
signal.signal(signal.SIGTERM, on_signal)
signal.signal(signal.SIGINT, on_signal)
workers = [threading.Thread(target=worker, args=(i,)) for i in range(3)]
for w in workers:
w.start()
threading.Timer(0.5, os.kill, (os.getpid(), signal.SIGTERM)).start()
stop.wait() # main thread sleeps until a signal arrives
for w in workers:
w.join(timeout=5)
if w.is_alive():
print(f"{w.name} did not stop in time")
sys.exit(1)
print("all workers stopped")
main thread got SIGTERM
worker 0: saving progress and exiting
worker 1: saving progress and exiting
worker 2: saving progress and exiting
all workers stopped
Two details make this robust:
- The main thread waits in
stop.wait()rather than inw.join(). Both are interruptible, but waiting on the event keeps the main thread free to react to the signal right away. join(timeout=5)puts an upper bound on shutdown. A worker stuck in a blocking call gets reported instead of hanging the process forever. Marking threadsdaemon=Trueis the blunt alternative: daemon threads are simply abandoned when the main thread exits, with no cleanup.
See Stoppable Thread with a while Loop and Locks and synchronization for more on Event.
Press Ctrl+C again to force quit
A graceful shutdown can take a while. Many tools treat the first Ctrl+C as "stop soon" and a second one as "stop now":
import os
import signal
import threading
import time
stop_requested = False
def on_sigint(signum, frame):
global stop_requested
if stop_requested:
print("second Ctrl+C: aborting")
raise KeyboardInterrupt
stop_requested = True
print("stopping after the current batch, press Ctrl+C again to abort")
signal.signal(signal.SIGINT, on_sigint)
# simulate the user pressing Ctrl+C twice
pid = os.getpid()
threading.Timer(0.3, os.kill, (pid, signal.SIGINT)).start()
threading.Timer(0.5, os.kill, (pid, signal.SIGINT)).start()
try:
batch = 0
while not stop_requested:
batch += 1
for item in range(4):
print(f"batch {batch} item {item}")
time.sleep(0.15)
print("stopped cleanly")
except KeyboardInterrupt:
print("aborted in the middle of a batch")
batch 1 item 0
batch 1 item 1
stopping after the current batch, press Ctrl+C again to abort
batch 1 item 2
batch 1 item 3
second Ctrl+C: aborting
aborted in the middle of a batch
atexit: what runs and what doesn't
atexit.register(func) registers a function to run when the interpreter exits. It's a good place for "flush and close" logic, but be clear about when it runs:
| How the process ends | finally / with |
atexit |
|---|---|---|
| main script finishes | yes | yes |
sys.exit() / uncaught exception |
yes | yes |
| Ctrl+C with default handler | yes | yes |
SIGTERM with default handler |
no | no |
SIGTERM with handler that calls sys.exit() |
yes | yes |
os._exit() |
no | no |
SIGKILL, power loss, OOM killer |
no | no |
Because SIGKILL can't be handled, a program that must survive crashes needs crash-safe storage (write to a temporary file then os.replace() it, use a database with transactions) rather than relying on cleanup code.
asyncio programs
In asyncio code, use loop.add_signal_handler() instead of signal.signal(). The callback runs as a normal event loop callback, not in the middle of arbitrary bytecode, so it can safely touch loop objects such as events, futures and tasks. The usual shape is: the signal sets an asyncio.Event, main() waits for it, then cancels the running tasks and awaits them so their cleanup code runs:
import asyncio
import os
import signal
async def worker(name):
try:
while True:
print(f"{name}: tick")
await asyncio.sleep(0.4)
except asyncio.CancelledError:
print(f"{name}: cancelled, closing connections")
await asyncio.sleep(0.1) # async cleanup is allowed here
raise
async def main():
stop = asyncio.Event()
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, stop.set)
tasks = [asyncio.create_task(worker(f"w{i}")) for i in range(2)]
loop.call_later(0.6, os.kill, os.getpid(), signal.SIGTERM)
await stop.wait()
print("signal received, cancelling tasks")
for t in tasks:
t.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
print("shutdown complete")
asyncio.run(main())
w0: tick
w1: tick
w0: tick
w1: tick
signal received, cancelling tasks
w0: cancelled, closing connections
w1: cancelled, closing connections
shutdown complete
Re-raise CancelledError after cleanup; swallowing it confuses asyncio and anything awaiting the task. loop.add_signal_handler() is available only on Unix.
Even without your own handler, asyncio.run() (Python 3.11+) handles Ctrl+C reasonably: it cancels the main task, lets it run its except CancelledError and finally blocks, and then raises KeyboardInterrupt:
import asyncio
import os
import signal
async def main():
loop = asyncio.get_running_loop()
loop.call_later(0.3, os.kill, os.getpid(), signal.SIGINT) # like Ctrl+C
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
print("main() cancelled by Ctrl+C, cleaning up")
raise
finally:
print("finally in main()")
try:
asyncio.run(main())
except KeyboardInterrupt:
print("asyncio.run raised KeyboardInterrupt")
main() cancelled by Ctrl+C, cleaning up
finally in main()
asyncio.run raised KeyboardInterrupt
This does nothing for SIGTERM, which still kills the process, so services should install handlers for both. Web frameworks and servers such as uvicorn, gunicorn and aiohttp already install their own SIGTERM/SIGINT handlers and expose startup/shutdown hooks; use those hooks instead of fighting the framework's handlers. See Asyncio Module for more on tasks.
Stopping child processes
subprocess.Popen has three methods for signalling a child: send_signal(sig), terminate() (sends SIGTERM) and kill() (sends SIGKILL). The standard escalation is to ask politely, wait with a deadline, then force:
import signal
import subprocess
import sys
child = subprocess.Popen(
[sys.executable, "-c", "import time; time.sleep(60)"],
)
child.terminate() # sends SIGTERM (TerminateProcess on Windows)
try:
child.wait(timeout=5)
except subprocess.TimeoutExpired:
child.kill() # SIGKILL: cannot be caught or ignored
child.wait()
print("returncode:", child.returncode)
if child.returncode < 0:
print("killed by", signal.Signals(-child.returncode).name)
returncode: -15
killed by SIGTERM
When you press Ctrl+C, the terminal sends SIGINT to every process in the foreground process group, which includes children started with subprocess. Signals sent with kill <pid> go only to that one process, though, so a supervisor that gets SIGTERM must pass it on to its children. Starting children with start_new_session=True puts them in their own session and process group, so the parent fully controls when and how they get stopped:
import os
import signal
import subprocess
import sys
import time
children = []
def forward(signum, frame):
print(f"parent: forwarding {signal.Signals(signum).name} to {len(children)} children", flush=True)
for p in children:
p.send_signal(signum)
signal.signal(signal.SIGTERM, forward)
child_code = """
import signal, sys, time
def bye(signum, frame):
print(f"child {sys.argv[1]}: graceful exit", flush=True)
sys.exit(0)
signal.signal(signal.SIGTERM, bye)
time.sleep(60)
"""
for i in range(2):
children.append(subprocess.Popen(
[sys.executable, "-c", child_code, str(i)],
start_new_session=True, # own process group: terminal Ctrl+C won't reach it
))
time.sleep(0.5)
os.kill(os.getpid(), signal.SIGTERM) # someone runs `kill <parent pid>`
for p in children:
p.wait()
print("parent: children exited with", [p.returncode for p in children])
parent: forwarding SIGTERM to 2 children
child 0: graceful exit
child 1: graceful exit
parent: children exited with [0, 0]
multiprocessing workers are child processes too. Pool.terminate() and Process.terminate() send SIGTERM; for a graceful stop, signal the workers through a multiprocessing.Event or a sentinel value on their queue, exactly like the thread example above. See Subprocess Library for more on subprocess.
Other useful signals
SIGHUP: reload configuration
Daemons traditionally reload their configuration on SIGHUP instead of restarting. Once again the handler only sets a flag, and the main loop does the actual reload at a safe point:
import json
import os
import signal
import time
CONFIG_FILE = "app.json"
config = {}
reload_requested = False
def load_config():
global config
with open(CONFIG_FILE) as f:
config = json.load(f)
print("loaded config:", config)
def on_sighup(signum, frame):
global reload_requested
reload_requested = True # do the real work outside the handler
signal.signal(signal.SIGHUP, on_sighup)
with open(CONFIG_FILE, "w") as f:
json.dump({"log_level": "info"}, f)
load_config()
for tick in range(4):
if reload_requested:
reload_requested = False
load_config()
print(f"tick {tick}, log_level={config['log_level']}")
if tick == 1: # an admin edits the file and runs `kill -HUP <pid>`
with open(CONFIG_FILE, "w") as f:
json.dump({"log_level": "debug"}, f)
os.kill(os.getpid(), signal.SIGHUP)
time.sleep(0.1)
os.remove(CONFIG_FILE)
loaded config: {'log_level': 'info'}
tick 0, log_level=info
tick 1, log_level=info
loaded config: {'log_level': 'debug'}
tick 2, log_level=debug
tick 3, log_level=debug
SIGUSR1: dump stack traces of a running process
When a service seems stuck, faulthandler.register() lets you ask it where every thread currently is, without stopping it. The dump is written by C code directly to stderr, so it works even when the main thread is blocked and can't run Python handlers:
import faulthandler
import os
import signal
import threading
import time
faulthandler.register(signal.SIGUSR1, all_threads=True)
def background():
time.sleep(1)
threading.Thread(target=background, name="bg").start()
time.sleep(0.1)
os.kill(os.getpid(), signal.SIGUSR1) # from a shell: kill -USR1 <pid>
time.sleep(0.1)
print("program keeps running")
Thread 0x000074b89e8ff6c0 [bg] (most recent call first):
File "/tmp/app/dump.py", line 10 in background
File "/usr/lib/python3.14/threading.py", line 1024 in run
File "/usr/lib/python3.14/threading.py", line 1082 in _bootstrap_inner
File "/usr/lib/python3.14/threading.py", line 1044 in _bootstrap
Current thread 0x000074b89ef0f1c0 [python3] (most recent call first):
File "/tmp/app/dump.py", line 14 in <module>
program keeps running
Thread names in the dump were added in Python 3.14; older versions show only thread ids. See Stack traces for more.
SIGALRM: timeouts
signal.setitimer() (or the whole-second signal.alarm()) delivers SIGALRM after a delay. Raising an exception from its handler gives you a timeout for code that has no timeout parameter of its own:
import signal
import time
class Timeout(Exception):
pass
def on_alarm(signum, frame):
raise Timeout()
signal.signal(signal.SIGALRM, on_alarm)
def slow_operation():
time.sleep(5)
return "finished"
signal.setitimer(signal.ITIMER_REAL, 0.5) # fire SIGALRM in 0.5 s
try:
print(slow_operation())
except Timeout:
print("timed out after 0.5 s")
finally:
signal.setitimer(signal.ITIMER_REAL, 0) # cancel the timer
timed out after 0.5 s
There is only one alarm timer per process, it works only in the main thread, and it's Unix-only, so prefer real timeouts (subprocess.run(timeout=...), socket.settimeout(), asyncio.timeout()) where they exist.
Ignoring and restoring signals
signal.SIG_IGN ignores a signal and signal.SIG_DFL restores the default action:
import os
import signal
import time
signal.signal(signal.SIGTERM, signal.SIG_IGN)
os.kill(os.getpid(), signal.SIGTERM)
time.sleep(0.1)
print("SIGTERM was ignored")
signal.signal(signal.SIGTERM, signal.SIG_DFL) # restore default: terminate
try:
signal.signal(signal.SIGKILL, signal.SIG_IGN)
except OSError as e:
print("OSError:", e)
print(len(signal.valid_signals()), "valid signals on this platform")
SIGTERM was ignored
OSError: [Errno 22] Invalid argument
62 valid signals on this platform
Ignored signals are inherited by child processes across exec, while Python handler functions are not (children start with the defaults). Ignoring SIGTERM is rarely a good idea: whoever sent it will usually follow up with SIGKILL.
Windows
Windows has no real signals. Python emulates a few of them:
import signal
import subprocess
import sys
print(sorted(s.name for s in signal.valid_signals()))
child_code = """
import signal, time
signal.signal(signal.SIGTERM, lambda *a: print("handler ran"))
try:
time.sleep(30)
finally:
print("finally ran")
"""
p = subprocess.Popen([sys.executable, "-c", child_code])
p.terminate()
p.wait()
print("returncode:", p.returncode)
['SIGABRT', 'SIGBREAK', 'SIGFPE', 'SIGILL', 'SIGINT', 'SIGSEGV', 'SIGTERM']
returncode: 1
Things to know:
- Ctrl+C in a console delivers
SIGINT(asKeyboardInterrupt), and Ctrl+Break deliversSIGBREAK. Handlers for both work as on Unix. - A
SIGTERMhandler can be installed, but nothing external ever triggers it.Popen.terminate(),Popen.kill()andos.kill(pid, signal.SIGTERM)all callTerminateProcess(), which kills the process instantly with no cleanup, likeSIGKILL. (terminate()sets exit code 1;os.kill(pid, sig)usessigas the exit code.) - To ask another console process to stop gracefully, start it with
creationflags=subprocess.CREATE_NEW_PROCESS_GROUPand sendsignal.CTRL_BREAK_EVENTwithsend_signal(); the child sees it asSIGBREAK. This only works between processes that share a console. SIGHUP,SIGUSR1,SIGALRM,loop.add_signal_handler()andstart_new_sessionare not available.
Cross-platform services often use a different shutdown channel on Windows, such as a socket, a named pipe or the Windows service control manager.
Containers and process managers
docker stop, Kubernetes and systemd all send SIGTERM, wait a grace period (10 seconds by default for Docker, 30 for Kubernetes, 90 for systemd), then send SIGKILL. A few container-specific gotchas:
- Use the exec form in a Dockerfile:
CMD ["python", "app.py"]. The shell formCMD python app.pyruns Python under/bin/sh, which receivesSIGTERMand does not forward it, so your handler never runs and the container is killed after the grace period. - PID 1 is special. The kernel doesn't apply default signal actions to PID 1 for signals it has no handler for, so a Python process running as PID 1 without a
SIGTERMhandler just ignoresdocker stopuntilSIGKILLarrives. Install a handler, or run under a tiny init such asdocker run --init(tini). - Finish within the grace period. Use timeouts on joins and waits so shutdown completes before
SIGKILLcuts it short.
Checklist
- Handle both
SIGINTandSIGTERM; by defaultSIGTERMskips all cleanup. - For scripts, a handler that calls
sys.exit(128 + signum)is enough to makefinally,withandatexitrun. - For services, have the handler set a flag or
Eventand stop at a safe point in the main loop. - Keep handlers tiny. Don't do I/O, logging or locking inside them.
- Handlers run only in the main thread; stop worker threads with an
Eventandjoin(timeout=...). - In
asyncio, useloop.add_signal_handler(), cancel tasks and await them. - Stop children with
terminate(),wait(timeout=...), thenkill(); forward signals to children you started in a new session. - Put a deadline on the whole shutdown, and assume
SIGKILLcan still happen.