What signals are
Signals predate the C standard library as a notification mechanism for exceptional
events. A signal has a number and a name. When the kernel delivers signal N to a
process, it interrupts the process at whatever instruction it's currently executing
and jumps to the registered signal handler. When the handler returns, execution
resumes where it was interrupted (usually — some syscalls return early with
EINTR).
Common signals
| signal | default action | typical cause |
|---|---|---|
| SIGINT (2) | terminate | Ctrl+C in terminal |
| SIGTERM (15) | terminate | kill command default |
| SIGKILL (9) | terminate (uncatchable) | kill -9, OOM killer |
| SIGSEGV (11) | terminate + core dump | invalid memory access |
| SIGCHLD (17) | ignore | child process exited |
| SIGALRM (14) | terminate | alarm() timer expired |
| SIGPIPE (13) | terminate | write to broken pipe |
kill -9 always works.
Installing a handler with sigaction
signal() is the old API — its behavior is implementation-defined
in several ways. Use sigaction() instead, which is fully specified
by POSIX and gives more control.
Async-signal safety
Signal handlers run asynchronously — they can interrupt your code at any point,
including in the middle of a malloc call or a printf call.
Most library functions are not async-signal-safe because they use internal locks
or global state. Calling printf from a signal handler can deadlock
if the signal arrived while printf held its internal lock.
The POSIX standard lists the async-signal-safe functions. The safe pattern for
signal handlers: set a volatile sig_atomic_t flag, then check and
act on that flag in your main loop. Keep handlers minimal.
printf, malloc, or free from a signal handler.
These functions are not async-signal-safe. The safe alternatives are
write() (for output) and setting a sig_atomic_t flag
(for state). Everything else should happen outside the handler.
Sending signals
Signals interrupt a process asynchronously — keep handlers minimal, use sig_atomic_t flags, and never call non-async-signal-safe functions inside them.