Part ofSystems Programming Companion, week 9
Signal Handling
Signals are how Unix delivers asynchronous notifications. Hit Ctrl+C in a terminal? The kernel pings the foreground process with SIGINT. A child process exits? The parent gets SIGCHLD. Touch memory you shouldn't? SIGSEGV. Signals sit at the bedrock of how Unix processes hold conversations with the kernel — and with each other.
What Signals Are
A signal is a small integer the kernel delivers to a process. When it lands, the process has three choices:
- Handle it: Execute a custom signal handler function
- Ignore it: Discard the signal (not possible for SIGKILL and SIGSTOP)
- Default action: Let the OS perform the default (usually terminate the process)
Common signals:
| Signal | Number | Default Action | Triggered By |
|---|---|---|---|
| SIGINT | 2 | Terminate | Ctrl+C |
| SIGTERM | 15 | Terminate | kill command |
| SIGKILL | 9 | Terminate | Cannot be caught |
| SIGSEGV | 11 | Core dump | Invalid memory access |
| SIGCHLD | 17 | Ignore | Child process exited |
| SIGALRM | 14 | Terminate | alarm() timer expired |
| SIGPIPE | 13 | Terminate | Write to broken pipe |
| SIGHUP | 1 | Terminate | Terminal closed |
signal() - The Simple Way
signal() wires up a handler for a particular signal:
#include <signal.h>#include <stdio.h>#include <stdlib.h>
volatile sig_atomic_t got_signal = 0;
void handler(int signum) { got_signal = 1;}
int main() { signal(SIGINT, handler);
printf("Press Ctrl+C to trigger the signal...\n"); while (!got_signal) { // busy wait (in production, block the signal and use sigsuspend(), shown below) } printf("Caught SIGINT! Exiting gracefully.\n"); return 0;}volatile sig_atomic_t is the only type the standard guarantees you can read and write safely from a signal handler. volatile stops the compiler from optimising your reads into the bin. sig_atomic_t promises that the load and store happen indivisibly.
sigaction() - The Right Way
signal() has a portability problem: every Unix flavour does it slightly differently. sigaction() is the dependable, modern replacement:
#include <signal.h>#include <stdio.h>#include <string.h>#include <unistd.h>
volatile sig_atomic_t shutdown_requested = 0;
void handle_sigterm(int signum) { shutdown_requested = 1;}
int main(void) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = handle_sigterm; sigemptyset(&sa.sa_mask); sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL);
// Hold both signals back so they can only be delivered inside sigsuspend sigset_t blocked, old_mask; sigemptyset(&blocked); sigaddset(&blocked, SIGTERM); sigaddset(&blocked, SIGINT); sigprocmask(SIG_BLOCK, &blocked, &old_mask);
printf("Server running. PID: %d\n", getpid()); while (!shutdown_requested) { sigsuspend(&old_mask); // Unblock and sleep in one atomic step } sigprocmask(SIG_SETMASK, &old_mask, NULL);
printf("Shutting down gracefully...\n"); return 0;}sa_mask says which signals to block while the handler runs. sigemptyset means "block nothing beyond what's already blocked."
Why not just while (!shutdown_requested) pause();? Because of a gap one instruction wide. Suppose SIGTERM lands after the loop has checked the flag and found it 0, but before pause() starts. The handler runs and sets the flag, then pause() goes to sleep waiting for a signal that has already come and gone. The process sleeps until something else wakes it, which could be never. This is the classic lost wakeup, and it'll survive every test you throw at it, then strike once a month in production.
sigsuspend closes the gap. With the signals blocked, a SIGTERM that arrives during the check is held as pending rather than delivered. sigsuspend(&old_mask) then swaps in the old mask and goes to sleep as a single atomic operation, so a pending signal is delivered the instant it starts and the loop sees the flag. Two other fixes for the same problem are a self-pipe (the handler writes a byte to a pipe your event loop is watching) and, on Linux, signalfd, which turns signals into something you read.
sa_flags = 0 is deliberate here. Without SA_RESTART, a signal interrupts a blocking call such as read() or accept() with EINTR, and that's exactly what a shutdown signal should do: knock the server out of its blocking wait so it can notice the flag.
Signal Safety
Signal handlers can fire at any point in your program — mid-loop, mid-malloc, mid-anything. Which means most functions are flat-out unsafe to call from one. POSIX defines a short list of async-signal-safe functions you're allowed to use, including:
write()(but NOTprintf)_exit()(but NOTexit())signal(),sigaction()close(),read(),open()
// WRONG: printf is not signal-safevoid bad_handler(int sig) { printf("Got signal %d\n", sig); // Can deadlock or corrupt state}
// RIGHT: use write() or just set a flagvoid good_handler(int sig) { const char msg[] = "Signal received\n"; write(STDOUT_FILENO, msg, sizeof(msg) - 1);}Safest play: set a flag in the handler, check that flag from the main loop. Done.
Why can it deadlock? The handler runs on the same thread it interrupted, so any lock that thread already holds is still held. Here the signal lands while malloc has its arena lock, and the handler calls something that allocates too (an unsafe printf can do exactly that the first time it sets up stdout's buffer):
The same trap exists for stdout's internal lock, and if the lock weren't there at all you'd get a half-updated free list instead of a hang.
Graceful Shutdown Pattern
Graceful shutdown is the workhorse pattern for signal handling. A server catches SIGTERM or SIGINT, then politely tears everything down — connections closed, buffers flushed, resources returned:
#include <signal.h>#include <stdio.h>#include <string.h>#include <unistd.h>#include <stdbool.h>
volatile sig_atomic_t running = 1;
void shutdown_handler(int sig) { running = 0;}
void setup_signals(void) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); // sa_sigaction and other fields must not be stack garbage sa.sa_handler = shutdown_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL);
// Ignore SIGPIPE (common for network servers) signal(SIGPIPE, SIG_IGN);}
int main() { setup_signals();
// Open resources FILE *log = fopen("server.log", "a");
while (running) { // Accept connections, process requests sleep(1); }
// Clean shutdown fprintf(log, "Server shutting down\n"); fclose(log); printf("Goodbye\n"); return 0;}A real server usually listens for more than one signal, and each wants a different response. SIGTERM means "finish what you're doing, then exit". SIGUSR1 is the usual convention for "reopen your log file", sent after logrotate has moved the old one aside. Both handlers below do the same tiny job, setting a flag. The main loop decides what to do about it, between requests, where calling printf or fopen is perfectly safe.
You can't poke a program in the runner from outside, so this one signals itself with kill(getpid(), ...) halfway through a request. When a process sends itself a signal that isn't blocked, POSIX guarantees the handler has run before kill returns.
Request 4 still prints finished. The handler ran the instant SIGTERM arrived, but setting a flag interrupts nothing, so the request completes and the loop bows out at its next check.
Exercise: build the real thing on your own machine. Accept TCP connections in a loop and append a line per request to server.log. On SIGTERM, finish the request in progress and exit; on SIGUSR1, close and reopen server.log. To test the second part, run mv server.log server.log.1, then kill -USR1 <pid>, and check that new lines land in a fresh server.log. Then think about accept(). With sa_flags = 0, either signal knocks it out with EINTR. That's what you want for SIGTERM, but is it what you want for SIGUSR1?
Child Reaping with SIGCHLD
When a child exits, it lingers as a zombie until the parent calls wait(). Install a SIGCHLD handler and you can reap them the moment they go:
void sigchld_handler(int sig) { int saved_errno = errno; // waitpid may overwrite errno; the code we interrupted may be reading it int status; // Reap all available zombie children while (waitpid(-1, &status, WNOHANG) > 0) { // Child reaped } errno = saved_errno;}
int main() { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = sigchld_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; // Restart interrupted system calls sigaction(SIGCHLD, &sa, NULL);
// Fork children as needed...}For a handler like this one, which should go unnoticed by the rest of the program, use SA_RESTART. Without it, a child exiting mid-read() or mid-accept() makes the call return early with errno == EINTR, and suddenly you're sprinkling retry loops all through your codebase. The shutdown handler earlier left it off on purpose, because there the interruption is the point. Pick per signal.
Blocking Signals
Sometimes you need an uninterruptible run of code:
sigset_t block_set, old_set;sigemptyset(&block_set);sigaddset(&block_set, SIGINT);sigaddset(&block_set, SIGTERM);
// Block SIGINT and SIGTERMsigprocmask(SIG_BLOCK, &block_set, &old_set);
// Critical section - no interruption possibleupdate_shared_data();
// Restore previous signal masksigprocmask(SIG_SETMASK, &old_set, NULL);Think of it as a mutex for signals. The critical section runs to completion, no signal can muscle in halfway.
Self-Pipe Trick
A favourite technique for letting select()/poll()/epoll() event loops talk to signal handlers is the self-pipe trick:
int signal_pipe[2];
void handler(int sig) { char c = sig; write(signal_pipe[1], &c, 1);}
int main() { pipe(signal_pipe); // Set signal_pipe fds to non-blocking // Add signal_pipe[0] to your poll/epoll set // When it becomes readable, a signal arrived}Async signals get translated into plain file-descriptor events your event loop already knows how to handle. Modern Linux ships signalfd(), which does this natively without the pipe trick.