FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Linux Signals & Signal Handlers

Asynchronous signal delivery, signal masks, reentrant handlers, sigaction(), and graceful process termination.

Freshness: current•15 min read•Computer Science and Programming

Key Learning Outcomes

  • ✓Implement safe signal handlers for graceful process shutdown
  • ✓Manage process signal masks and signalfd file descriptors
Full Technical Reference Document

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.

Process / kernel raises SIGTERM
Kernel marks thread pending signal bit
Mode switch checks unmasked signals
sigaction handler or signalfd wakes
Flush sockets/WAL cleanly before _exit
Conceptual teaching model synthesized from:Linux Kernel Kernel.org Official Architecture & Systems DocumentationSite Reliability Engineering

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 sigaction handlers (never malloc, printf, or Python loggers).
  • Explain why container processes running as Linux PID 1 silently ignore default SIGTERM rules 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 / MechanismCatchable?Interrupt Behavior & Delivery ScopeProduction Container Engineering Impact
SIGTERM (15)Yes (sigaction / asyncio loop handler)Polite termination notice delivered by systemd / Kubernetes Pod stopClose listening sockets, finish active inference SSE turns, flush buffers cleanly
SIGKILL (9)No (kernel executes immediately)Unconditional process destruction without cleanup hooksSent after Kubernetes terminationGracePeriodSeconds (30s) expires
SIGHUP / SIGUSR1YesTerminal hangup or custom user signal cleanlyZero-downtime reload of TLS certs or Nginx/Gunicorn workers
SIGCHLDYes (default ignored cleanly!)Sent to parent when forked child dies cleanlyParent MUST call waitpid(-1, WNOHANG) inside loop cleanly to reap Zombies!
SIGPIPEYes (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 calling malloc() inside the signal callback immediately deadlocks the global libc heap mutex permanently.
  • Forgetting SIGPIPE Ignore (SIG_IGN) on Network Servers: Dropping connections mid-SSE flush delivers SIGPIPE, silently killing unprepared C/C++ network daemons instantly cleanly on client tab close!
  • Ignoring EINTR on Interrupted Blocking Syscalls: When sigaction interrupts read() or accept() cleanly, un-wrapped blocking loops crash (errno == EINTR) unless configured with SA_RESTART or retry loops.
  • Unregistered SIGTERM Handlers on Container PID 1: Docker ENTRYPOINT ["sh", "-c", ...] fails cleanly to forward SIGTERM down cleanly to Python/Node child apps unless using exec or init: 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.

Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next