Signals let an operating system notify a process about interruption, termination, and other events. Python handlers run in the main thread between interpreter instructions.

Practical example

import signal
import time

stopping = False

def request_stop(signum, frame):
    global stopping
    stopping = True

signal.signal(signal.SIGINT, request_stop)
while not stopping:
    time.sleep(0.2)
print("shutdown requested")

Short handler, predictable shutdown

The example only changes a flag. The loop notices the request, stops accepting work, and closes resources in order. Long-running native code can delay handler execution.

SIGINT and SIGTERM

SIGINT commonly comes from a terminal. Unix services should also consider SIGTERM. Availability and behavior differ on Windows, so test every supported platform.

Working with asyncio

Async loops provide signal APIs on compatible platforms. Schedule a shutdown coroutine instead of blocking the handler, and enforce an external timeout for a process that does not stop.

Keep learning

Strengthen the foundation with safe subprocess execution. The official Python documentation, accessed July 22, 2026, documents the API, limitations, and version differences.