Mental model
Linux Signals are asynchronous notifications delivered by the kernel to a process to inform it of an event (e.g. user interruption SIGINT, termination request SIGTERM, segmentation fault SIGSEGV).
Theory
SIGTERM(15): Graceful termination request. Can be caught, handled, or ignored by application signal handlers to close sockets and flush transactions.SIGKILL(9): Immediate forced process destruction by kernel. CANNOT be caught or ignored.- Async-Signal-Safe Functions: Functions that can be safely invoked inside a signal handler (e.g.
write(),_exit()). Non-reentrant functions likeprintf()ormalloc()MUST NOT be called in signal handlers.
Alternatives and trade-offs
- Classic Signal Handlers (
sigaction): Interrupts execution flow asynchronously; restricted to calling async-signal-safe functions. signalfd()File Descriptors: Converts signal notifications into standard file descriptor read events; allows processing signals synchronously inepollevent loops.
Failure modes and misconceptions
- Deadlocks from Invoking
printformallocin Handlers: Invokingprintf()ormalloc()inside a signal handler while the main thread holds an internal heap lock causes permanent process deadlocks. - Ignoring
SIGTERMin Container PID 1: Container processes running as PID 1 that fail to registerSIGTERMhandlers cause container runtimes to wait 10 seconds before forcibly destroying the container withSIGKILL.
Decision scenario
Register explicit SIGTERM signal handlers using sigaction or signalfd in all containerized applications to enable graceful socket closure and transaction flushing during rollouts.
Learning outcomes
- Structure safe asynchronous signal handling using
sigaction. - Distinguish graceful
SIGTERMtermination requests from uncatchableSIGKILL. - Eliminate handler deadlocks by avoiding non-reentrant functions like
malloc()orprintf().
Trade-offs
Signals provide essential process lifecycle control, but require strict adherence to async-signal-safe programming constraints inside handler functions.