Mental model
Linux signals are asynchronous software interrupts delivered by the kernel into user processes to announce external lifecycle events (SIGTERM, SIGINT, SIGHUP), timer expirations, or hardware faults (SIGSEGV, SIGPIPE). Because kernel signal delivery preempts the normal instruction pointer arbitrarily—potentially while the main thread holds internal malloc or mutex locks—handlers must write strictly async-signal-safe flags (volatile sig_atomic_t) or route signals synchronously onto event loops via signalfd / self-pipe tricks.
Learning outcomes
- Contrast catchable graceful termination signals (
SIGTERM,SIGINT,SIGHUP) cleanly against uncatchable immediate kernel termination (SIGKILL,SIGSTOP). - Prevent random heap corruption and deadlocks by calling strictly POSIX async-signal-safe functions inside
sigactionhandlers (never malloc, printf, or Python loggers). - Explain why container processes running as Linux PID 1 silently ignore default
SIGTERMrules cleanly unless explicit handlers run or tini/dumb-init reaps cleanly.
Theory
Handling shutdown cleanly inside distributed LLM inference gateways or Postgres workers requires knowing two crucial kernel semantics:
| Signal / Mechanism | Catchable? | Interrupt Behavior & Delivery Scope | Production Container Engineering Impact |
|---|---|---|---|
SIGTERM (15) | Yes (sigaction / asyncio loop handler) | Polite termination notice delivered by systemd / Kubernetes Pod stop | Close listening sockets, finish active inference SSE turns, flush buffers cleanly |
SIGKILL (9) | No (kernel executes immediately) | Unconditional process destruction without cleanup hooks | Sent after Kubernetes terminationGracePeriodSeconds (30s) expires |
SIGHUP / SIGUSR1 | Yes | Terminal hangup or custom user signal cleanly | Zero-downtime reload of TLS certs or Nginx/Gunicorn workers |
SIGCHLD | Yes (default ignored cleanly!) | Sent to parent when forked child dies cleanly | Parent MUST call waitpid(-1, WNOHANG) inside loop cleanly to reap Zombies! |
SIGPIPE | Yes (default terminates PID!) | Writing cleanly into closed client socket (aborted curl/SSE) | Backend servers ignore SIGPIPE (SIG_IGN) and handle EPIPE error return instead! |
Notice also Kubernetes PID 1 special kernel protection: by default in Linux, PID 1 (init) drops any signal carrying SIG_DFL (default action) if no explicit handler is registered! Running a naive binary or shell script cleanly directly as container PID 1 causes docker stop / Kubernetes Pod drains to hang uselessly for 30 seconds before getting SIGKILL-ed cleanly! Using tini / dumb-init or registering Python/Go signal handlers cleanly fixes container termination latency instantaneously.
c#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <signal.h>#include <sys/signalfd.h>#include <unistd.h>/* Option A: Async-signal-safe flag + self-pipe for sigaction handlers */static volatile sig_atomic_t shutdown_requested = 0;static void handle_sigterm_safe(int signo) {int saved_errno = errno;(void)signo;shutdown_requested = 1;/* Only async-signal-safe POSIX functions allowed here (write/sig_atomic_t), NEVER malloc/printf! */const char msg[] = "SIGTERM queued\n";(void)write(STDERR_FILENO, msg, sizeof(msg) - 1);errno = saved_errno;}/* Option B (Linux preferred for epoll servers): block signals & read via synchronous signalfd() */int create_graceful_signalfd(void) {sigset_t mask;sigemptyset(&mask);sigaddset(&mask, SIGTERM);sigaddset(&mask, SIGINT);sigprocmask(SIG_BLOCK, &mask, NULL);return signalfd(-1, &mask, SFD_NONBLOCK | SFD_CLOEXEC);}
Trade-offs
Using classic sigaction with volatile sig_atomic_t flags (plus POSIX SA_RESTART) works portably across Linux, macOS, and BSD environments without external dependencies, demanding strict care cleanly never to invoke allocating libc functions or CPython C-API calls inside interrupt context. On Linux event-loop servers (C/Rust epoll, libuv, Python loop.add_signal_handler), signalfd or pipe wakeup converts unpredictable interrupt callbacks cleanly into safe synchronous file-descriptor read events handled uniformly beside client sockets cleanly!
Failure modes and misconceptions
- Calling
printf(),malloc(), or Python Logging in Handlers: Preempting the main thread mid-heap-allocation and callingmalloc()inside the signal callback immediately deadlocks the global libc heap mutex permanently. - Forgetting
SIGPIPEIgnore (SIG_IGN) on Network Servers: Dropping connections mid-SSE flush deliversSIGPIPE, silently killing unprepared C/C++ network daemons instantly cleanly on client tab close! - Ignoring
EINTRon Interrupted Blocking Syscalls: Whensigactioninterruptsread()oraccept()cleanly, un-wrapped blocking loops crash (errno == EINTR) unless configured withSA_RESTARTor retry loops. - Unregistered
SIGTERMHandlers on Container PID 1: DockerENTRYPOINT ["sh", "-c", ...]fails cleanly to forwardSIGTERMdown cleanly to Python/Node child apps unless usingexecorinit: true.
Decision scenario
A containerized C/C++ inference router drops connections mid-deploys cleanly cleanly instead of draining open streams, freezes occasionally when logs run inside crash handlers, and dies abruptly when SSE callers hang up! Ignore SIGPIPE at startup, replace handler fprintf() cleanly with a Linux signalfd() registered directly into epoll loop, run under exec (PID 1 direct forwarding or tini), and flush sockets deterministically on SIGTERM cleanly.