Self-pipe trick & signalfd
Turn signals into readable events that fit into an event loop.
By Invicly Tech, , in Linux System Programming. About 11 minutes to read.
In short
Handlers are awkward in programs built around an event loop. The self-pipe trick has the handler write one byte to a pipe that the loop watches, and Linux's signalfd goes further by letting you read signals from a descriptor. Either way, signals become ordinary events handled in normal code.
Explained simply
Many programs are built around an event loop: one place that waits for anything to happen, such as a new network connection or data on a socket, and then handles it. Signals do not fit this style. They interrupt the program at random moments instead of politely joining the queue of events.
The fix is to turn a signal into data. The oldest method is the self-pipe trick: the handler writes one byte into a pipe, and the event loop watches that pipe like any other input. When the byte arrives, the loop knows a signal came in and handles it in normal code, where every function is safe.
Linux has a cleaner way called signalfd. You tell the kernel "do not interrupt me with these signals, give them to me as a file instead". The kernel then puts each signal in a small record that you read from a file descriptor, together with details such as who sent it.
Both methods give the same big win: all your real work happens in one place, with no handler surprises. That makes servers easier to write and to reason about.
Press Play on a diagram to walk through it one step at a time.
- 1Block the signals
sigprocmask(SIG_BLOCK) for SIGINT, SIGTERM, SIGCHLD.
- 2Create a signalfd
signalfd(-1, &mask, SFD_CLOEXEC).
- 3Add it to the loop
Watch it with poll or epoll like a socket.
- 4Read events
read() returns struct signalfd_siginfo records.
- 5Handle in normal code
Reap children, reload config or shut down.
- Handler writes 1 byte
- Works on any Unix (eventfd: Linux)
- Needs careful non-blocking setup
- Used by libevent and libuv
- No handler at all
- Linux only
- Returns sender PID, UID, status
- Signals must be blocked in all threads
- One thread waits for signals
- Portable POSIX
- Fits thread-based programs
- Signals blocked in all threads
In depth
The self-pipe trick, step by step
Create a pipe at startup with pipe2 and the flags O_NONBLOCK and O_CLOEXEC. The handler does only one thing: write a single byte (often the signal number) to the write end, saving and restoring errno around it. The write end must be non-blocking, because a handler must never block; if the pipe is full, write fails with EAGAIN and that is fine, since a wake-up byte is already waiting.
The event loop adds the read end to poll or epoll. When it becomes readable, the loop reads until EAGAIN to drain all bytes, then checks its flags or the bytes it read and acts in normal code. Event libraries such as libevent and libuv use this method on systems without signalfd. On Linux, an eventfd can replace the pipe and saves one descriptor.
- Kernel to Handler: deliver SIGTERM1deliver SIGTERM
- Handler to Pipe: write 1 byte (non-blocking)2write 1 byte (non-blocking)
- Pipe to Event loop: read end becomes readable3read end becomes readable
- Event loop to Pipe: read until EAGAIN4read until EAGAIN
- 5shut down in normal codeEvent loop to Event loop: shut down in normal code
signalfd details that bite
signalfd(-1, &mask, SFD_NONBLOCK | SFD_CLOEXEC) creates the descriptor. Each read returns one or more struct signalfd_siginfo records of exactly 128 bytes; a buffer smaller than that fails with EINVAL. Useful fields are ssi_signo, ssi_pid, ssi_uid, ssi_code and, for SIGCHLD, ssi_status.
The signals must be blocked in every thread, or the kernel may deliver them the normal way to a thread that did not block them. Block them in main before creating any thread, because new threads inherit the mask. The second trap is exec: the blocked mask survives fork and exec, so a child you start would begin with SIGTERM and SIGINT blocked and could not be stopped. Unblock them in the child between fork and exec, or use posix_spawnattr_setsigmask.
- One signalfd can watch several signals at once
- Changing the mask: call signalfd again with the existing fd
- Reading the fd consumes the pending signal
Reaping children from an event loop
SIGCHLD is the signal you most often route into a loop, because a server that starts workers must reap them. Two rules apply. First, several child exits can merge into a single SIGCHLD, and ssi_pid only names one of them. So after any SIGCHLD event, loop on waitpid(-1, &st, WNOHANG) until it returns 0 (children left, none finished) or -1 with ECHILD (no children left).
Second, if you want a per-child event instead, Linux 5.3 added pidfd_open(pid, 0). It returns a descriptor that becomes readable when that exact child exits. Add it to epoll, and reap with waitid(P_PIDFD, fd, &info, WEXITED) on Linux 5.4 or later. This also avoids PID reuse races, because the descriptor always refers to the one process.
- 1signalfd readable
epoll reports the event.
- 2Read records
Until EAGAIN; merged signals look like one.
- 3waitpid WNOHANG loop
Repeat while it returns a PID.
- 4Update job table
Log the status, maybe restart a worker.
- 5Back to epoll_wait
No zombies remain.
Choosing a method
Use signalfd when your program is Linux-only and already uses epoll; it needs no handler code at all. Use the self-pipe trick, or an eventfd, when you need portability to macOS or the BSDs, or when a library already installed handlers you cannot remove. On BSD and macOS, kqueue has an EVFILT_SIGNAL filter that plays the same role.
A third option fits threaded programs: block the signals in all threads and dedicate one thread that loops on sigwaitinfo, handling each signal in normal code. Whatever you choose, keep one owner for each signal. Mixing an old-style handler and a signalfd for the same signal leads to signals that seem to vanish.
Learn it in 4 short steps
About 40m each. Track them with a timer in your plan.
- 1Implement the self-pipe trick~40m
- 2Block signals and create a signalfd~40m
- 3Read signalfd_siginfo structs~40m
- 4Handle SIGCHLD to reap children~40m
Key points
- Signals must be blocked first, otherwise they are delivered the normal way.
- One read can return several signalfd_siginfo records.
- After SIGCHLD, loop on waitpid with WNOHANG because several exits can merge into one signal.
- The self-pipe trick works on any Unix, not just Linux.
Key terms
Tap a card to flip it. 0/4 known
Examples
#include <signal.h>
#include <stdio.h>
#include <sys/signalfd.h>
#include <unistd.h>
int main(void) {
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGINT); sigaddset(&mask, SIGTERM);
sigprocmask(SIG_BLOCK, &mask, NULL);
int sfd = signalfd(-1, &mask, SFD_CLOEXEC);
struct signalfd_siginfo si;
if (read(sfd, &si, sizeof si) == sizeof si)
printf("got signal %u from pid %u\n", si.ssi_signo, si.ssi_pid);
return 0;
}Signals arrive as data on a descriptor instead of interrupting code.
An epoll loop that handles SIGTERM and SIGCHLD
This is the skeleton of a supervisor that starts workers. Step 1: block both signals before any threads exist. Step 2: create a non-blocking signalfd and add it to epoll. Step 3: in the loop, read signal records until EAGAIN. Step 4: SIGTERM clears the running flag; SIGCHLD triggers a waitpid loop that reaps every finished child. Error checks are shortened here; check every call in real code.
sigset_t m; sigemptyset(&m); sigaddset(&m, SIGTERM); sigaddset(&m, SIGCHLD);
if (sigprocmask(SIG_BLOCK, &m, NULL) < 0) { perror("sigprocmask"); return 1; }
int sfd = signalfd(-1, &m, SFD_NONBLOCK | SFD_CLOEXEC);
int ep = epoll_create1(EPOLL_CLOEXEC);
struct epoll_event ev = { .events = EPOLLIN, .data.fd = sfd };
if (sfd < 0 || ep < 0 || epoll_ctl(ep, EPOLL_CTL_ADD, sfd, &ev) < 0) { perror("setup"); return 1; }
for (int running = 1; running; ) {
struct epoll_event out[16];
int n = epoll_wait(ep, out, 16, -1);
for (int i = 0; i < n; i++) {
struct signalfd_siginfo si;
while (out[i].data.fd == sfd && read(sfd, &si, sizeof si) == sizeof si)
if (si.ssi_signo == SIGTERM) running = 0;
else while (waitpid(-1, NULL, WNOHANG) > 0) {}
}
}The self-pipe trick in portable code
Here the same idea works without signalfd. Step 1: create a non-blocking, close-on-exec pipe (pipe2 needs _GNU_SOURCE defined before the includes). Step 2: the handler writes the signal number as one byte and restores errno; a full pipe is harmless. Step 3: install it with SA_RESTART so normal calls are not disturbed. Step 4: when poll says the read end is readable, drain it and handle each signal in normal code.
static int pfd[2];
static void on_sig(int sig) {
int saved = errno;
unsigned char b = (unsigned char)sig;
ssize_t r = write(pfd[1], &b, 1); /* EAGAIN when full is fine */
(void)r; errno = saved;
}
/* setup */
if (pipe2(pfd, O_NONBLOCK | O_CLOEXEC) < 0) { perror("pipe2"); exit(1); }
struct sigaction sa = { .sa_handler = on_sig, .sa_flags = SA_RESTART };
sigemptyset(&sa.sa_mask);
sigaction(SIGTERM, &sa, NULL); sigaction(SIGHUP, &sa, NULL);
/* in the poll loop, when pfd[0] is readable: */
unsigned char b; while (read(pfd[0], &b, 1) == 1) handle_signal(b);Quick reference
- Block the signals first, then create the signalfd, then start threads
- Each signalfd read returns whole 128-byte struct signalfd_siginfo records
- Unblock signals in a child before exec, because the mask is inherited
- After SIGCHLD, loop waitpid(-1, &st, WNOHANG) until it stops returning PIDs
- Self-pipe: both ends non-blocking; the handler only writes one byte
- eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC) can replace the pipe on Linux
- pidfd_open gives one descriptor per child that becomes readable when it exits
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
Extend the explainer's signalfd example so it loops forever printing every SIGINT and exits only on SIGTERM.
- Exercise 2medium
Write a program that starts 3 children which sleep 1, 2 and 3 seconds, and reaps them through a signalfd for SIGCHLD, printing each PID and exit code.
- Exercise 3hard
Build a mini supervisor with epoll and a signalfd: it starts a worker command, restarts it whenever it exits with a non-zero code, and stops the worker and itself on SIGTERM.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is signalfd better than a signal handler?
- For event-loop programs on Linux, usually yes: all handling happens in normal code where any function is safe. For tiny programs, a handler that sets a flag is simpler.
- Does signalfd work on macOS?
- No, it is Linux-only. Use the self-pipe trick or kqueue with EVFILT_SIGNAL on macOS and the BSDs.
- Why does my child process ignore Ctrl-C after I used signalfd?
- The blocked signal mask was inherited across fork and exec. Unblock the signals in the child before calling exec.