sigaction, masks & async-signal safety
Install reliable handlers with sigaction that only do async-signal-safe work.
By Invicly Tech, , in Linux System Programming. About 12 minutes to read.
In short
sigaction installs a signal handler with well-defined behaviour, unlike the older signal function. A handler can interrupt your code anywhere, so it must only call async-signal-safe functions and usually just sets a flag. Signal masks let you block delivery during critical sections.
Explained simply
A signal handler is a function you write that runs when a signal arrives. It does not run in a nice, planned place. The kernel pauses your program wherever it happens to be, maybe in the middle of printf or malloc, runs your handler, and then lets the program continue as if nothing happened.
That surprise timing is the whole difficulty. If your main code was halfway through updating a list and the handler touches the same list, the list breaks. So the golden rule is: a handler should do almost nothing. Usually it just sets a flag, and the main code checks the flag at a safe moment.
sigaction is the function you use to install a handler. It lets you say exactly how the handler behaves: which other signals to hold back while it runs, whether interrupted system calls should restart, and whether you want extra information such as who sent the signal.
You can also tell the kernel "not now". Blocking a signal with sigprocmask is like putting a phone on silent: calls are not lost, they wait as missed calls, and you get them when you unblock. This lets you protect short critical sections of code.
Press Play on a diagram to walk through it one step at a time.
- Terminal to Kernel: Ctrl-C: SIGINT to the foreground group1Ctrl-C: SIGINT to the foreground group
- Kernel to Main code: Interrupt at the next return to user mode2Interrupt at the next return to user mode
- Kernel to Handler: Run handler(SIGINT) on the process stack3Run handler(SIGINT) on the process stack
- Handler to Main code: Set stop = 1 and return; main code resumes4Set stop = 1 and return; main code resumes
- Kernel to Main code: Blocked call returns EINTR or restarts with SA_RESTART5Blocked call returns EINTR or restarts with SA_RESTART
- Set a volatile sig_atomic_t flag
- write() a fixed message to a fd
- waitpid(-1, &st, WNOHANG) in a loop
- Save and restore errno
- _exit() for an emergency stop
- printf, puts, fprintf
- malloc, free, new strings
- exit() and atexit handlers
- Locking a pthread mutex
- syslog or most library calls
In depth
The fields of struct sigaction
sa_handler points to a simple handler void f(int sig), or holds SIG_DFL or SIG_IGN. If you set the SA_SIGINFO flag you fill sa_sigaction instead, a handler void f(int sig, siginfo_t *info, void *ctx), and info tells you si_pid and si_uid (who sent it), si_code (why) and, for SIGSEGV, si_addr (the bad address).
sa_mask lists extra signals to block while the handler runs. The signal being handled is blocked automatically unless you set SA_NODEFER, so a handler does not interrupt itself. Useful flags: SA_RESTART restarts many interrupted calls, SA_NOCLDSTOP stops SIGCHLD for stopped children, SA_NOCLDWAIT prevents zombies, SA_RESETHAND makes the handler one-shot, and SA_ONSTACK runs it on an alternate stack set with sigaltstack, which you need to handle stack overflows.
The old signal() function behaved differently on different systems; sigaction gives one defined behaviour everywhere.
- Always sigemptyset(&sa.sa_mask) or zero the struct first
- Check the return value of sigaction itself
- sigaction(sig, NULL, &old) reads the current setting
Why only async-signal-safe functions
Imagine main is inside malloc and holds malloc's internal lock. A signal arrives and your handler calls printf, which calls malloc, which tries to take the same lock. The lock is already held by the same thread, which is now stuck in the handler, so the program hangs forever. With other functions, the result is not a hang but quietly corrupted data.
A function is async-signal-safe if it is safe to call even when it interrupted itself. The list in signal-safety(7) includes write, read, open, close, _exit, kill, waitpid, sigaction, sigprocmask, sem_post and clock_gettime. It does not include printf, malloc, free, exit, syslog or pthread_mutex_lock. Safe functions may still change errno, so save errno at the start of a handler and restore it at the end.
- Main code to malloc lock: malloc() takes the lock1malloc() takes the lock
- malloc lock to Handler: signal arrives mid-malloc, handler runs2signal arrives mid-malloc, handler runs
- Handler to malloc lock: printf() calls malloc(), waits for the lock3printf() calls malloc(), waits for the lock
- malloc lock to Main code: lock owner is paused under the handler4lock owner is paused under the handler
- 5waits forever: deadlockHandler to Handler: waits forever: deadlock
volatile sig_atomic_t, and the pause() race
The C standard guarantees only one kind of shared variable: writing a volatile sig_atomic_t. volatile stops the compiler from keeping the value in a register, where the main loop would never see the handler's change. sig_atomic_t guarantees the write happens in one step. C11 lock-free atomics, such as atomic_int when atomic_is_lock_free says yes, are also allowed.
A common bug hides in this code: while (!flag) pause(). If the signal arrives after the check but before pause starts, the handler sets the flag, pause then sleeps, and nothing wakes it. The fix is sigsuspend: block the signal, check the flag, and call sigsuspend with the old mask. sigsuspend unblocks and sleeps in one atomic step, so the signal cannot slip into the gap.
Signal masks and critical sections
sigprocmask(how, &set, &old) changes the mask of the calling thread: SIG_BLOCK adds signals, SIG_UNBLOCK removes them, SIG_SETMASK replaces the whole mask. In threaded programs use pthread_sigmask, which works the same way per thread. A blocked signal is not lost; it stays pending and is delivered right after you unblock, at most once for standard signals. sigpending shows what is waiting.
The mask is inherited by fork and kept across exec. That is useful, but it is also a trap: if you block SIGTERM in a parent and then exec a child, the child starts with SIGTERM blocked and cannot be stopped politely. Restore the mask in the child before exec. Keep blocked sections short, for example around updating a shared data structure that a handler also reads.
- 1Block
sigprocmask(SIG_BLOCK, &set, &old).
- 2Update shared data
No handler can interrupt now.
- 3Signal arrives
Kept pending, not lost.
- 4Restore mask
sigprocmask(SIG_SETMASK, &old, NULL).
- 5Handler runs
Delivered right after unblocking.
EINTR and SA_RESTART
If a handler runs while your code is blocked in a slow system call, such as read on a pipe or socket, accept or waitpid, that call may fail with errno EINTR. With SA_RESTART set, the kernel restarts most of these calls for you. Some calls never restart, no matter what: poll, select, epoll_wait, nanosleep and sleep (which return early, sleep returning the time left), and socket calls that have a timeout set with SO_RCVTIMEO.
Sometimes you want EINTR. A program that blocks in read and should stop on SIGTERM can install its handler without SA_RESTART; read then fails with EINTR, the loop checks the flag and exits cleanly. Either way, robust code wraps blocking calls in a loop that retries on EINTR unless a stop flag is set.
- Retry pattern: do { n = read(fd, b, len); } while (n < 0 && errno == EINTR);
- With SA_RESTART, read on a slow device restarts; poll still returns EINTR
- Disk file reads are not slow calls and are not interrupted
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Install handlers with sigaction~50m
- 2Block signals with sigprocmask~50m
- 3Set a volatile sig_atomic_t flag~50m
- 4Use SA_RESTART to resume syscalls~50m
- 5Check the async-signal-safe function list~50m
Key points
- Use sigaction, not signal, for portable and predictable handlers.
- Inside a handler only call async-signal-safe functions such as write, never printf or malloc.
- Communicate with the main code through a volatile sig_atomic_t flag.
- SA_RESTART makes many interrupted system calls restart instead of failing with EINTR.
- sigprocmask blocks signals temporarily; they stay pending until unblocked.
Key terms
Tap a card to flip it. 0/6 known
Examples
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
static volatile sig_atomic_t stop = 0;
static void on_int(int sig) { (void)sig; stop = 1; }
int main(void) {
struct sigaction sa = { .sa_handler = on_int };
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, NULL);
while (!stop) sleep(1);
puts("clean shutdown");
return 0;
}Press Ctrl-C: the handler only sets a flag; cleanup happens in main.
Graceful shutdown on SIGINT and SIGTERM
This program reads from stdin until told to stop. Step 1: zero the struct and set the handler, which only stores the signal number. Step 2: put both signals in sa_mask so one handler cannot interrupt the other. Step 3: leave out SA_RESTART on purpose, so a blocked read fails with EINTR when a signal arrives. Step 4: the loop sees the flag and exits normally, where printing and cleanup are safe. Run it and press Ctrl-C.
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
static volatile sig_atomic_t got = 0;
static void on_stop(int sig) { got = sig; }
int main(void) {
struct sigaction sa; memset(&sa, 0, sizeof sa);
sa.sa_handler = on_stop; /* no SA_RESTART: read returns EINTR */
sigemptyset(&sa.sa_mask); sigaddset(&sa.sa_mask, SIGINT); sigaddset(&sa.sa_mask, SIGTERM);
if (sigaction(SIGINT, &sa, NULL) < 0 || sigaction(SIGTERM, &sa, NULL) < 0) { perror("sigaction"); return 1; }
char buf[256]; ssize_t n;
while (!got && ((n = read(STDIN_FILENO, buf, sizeof buf)) > 0 || (n < 0 && errno == EINTR))) {}
printf("stopping (signal %d), cleaning up\n", (int)got); return 0;
}Waiting for a signal without the race
You want to sleep until SIGUSR1 arrives. Step 1: block SIGUSR1 before checking the flag, so it cannot arrive in the gap. Step 2: check the flag. Step 3: sigsuspend(&old) atomically installs the old mask (SIGUSR1 unblocked) and sleeps; when the handler has run it returns with EINTR and the mask is blocked again. Step 4: loop until the flag is set, then restore the mask. Test it with kill -USR1 PID from another terminal.
static volatile sig_atomic_t got_usr1 = 0;
static void on_usr1(int s) { (void)s; got_usr1 = 1; }
/* in main, after installing on_usr1 with sigaction: */
sigset_t block, old;
sigemptyset(&block); sigaddset(&block, SIGUSR1);
sigprocmask(SIG_BLOCK, &block, &old); /* 1. close the gap */
while (!got_usr1) /* 2. check safely */
sigsuspend(&old); /* 3. unblock and sleep in one step */
sigprocmask(SIG_SETMASK, &old, NULL); /* 4. back to normal */
puts("got SIGUSR1");Quick reference
- Zero struct sigaction and call sigemptyset on sa_mask before filling it in
- SA_SIGINFO plus sa_sigaction gives you the sender PID in info->si_pid
- The handled signal is blocked during its own handler unless SA_NODEFER is set
- Save errno at the start of every handler and restore it at the end
- Use sigsuspend, not pause, to wait for a signal without a race
- poll, select, epoll_wait and nanosleep return EINTR even with SA_RESTART
- The signal mask survives fork and exec; reset it in the child before exec
- Use pthread_sigmask instead of sigprocmask in multithreaded programs
Common mistakes
- Calling printf, malloc or locking a mutex inside a handler.
- Ignoring EINTR from blocking calls when SA_RESTART is not set.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Install a SIGINT handler with sigaction that writes "caught" to stderr using write(), then keep the program alive with sleep in a loop. Press Ctrl-C three times.
- Exercise 2medium
Use SA_SIGINFO to print the PID and UID of whoever sends SIGUSR1, without calling printf in the handler.
- Exercise 3hard
Show that blocked signals merge: block SIGUSR1, send it to yourself 5 times, unblock, and count how many times the handler ran. Then repeat with SIGRTMIN and compare.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why use sigaction instead of signal?
- signal() has historically behaved differently between systems, for example resetting the handler after one use. sigaction lets you set the mask and flags explicitly, so the behaviour is the same everywhere.
- Can I use printf in a signal handler if I am careful?
- No. Even careful use can deadlock or corrupt output if the signal interrupts another stdio call. Use write with a fixed buffer, or set a flag and print from main.
- What does EINTR mean?
- Interrupted system call: a signal handler ran while the call was waiting. Retry the call, or treat it as a chance to check your stop flag.
- Do signal handlers run in a separate thread?
- No. The kernel borrows one existing thread of the process, pauses what it was doing, and runs the handler on that thread's stack.