Linux System Programming · beginner · ~8 min
Use alarm() to time-out a blocking operation.
alarm(n) asks the kernel to deliver SIGALRM to your process n seconds from now. The classic use is making a blocking syscall — read(), accept(), connect() — give up after a timeout: install a SIGALRM handler that does nothing (or sets a flag), call alarm(n), then issue the syscall. When SIGALRM fires the syscall returns EINTR.
alarm(0) cancels a pending alarm. For sub-second or repeating timers, use setitimer() or — modern Linux — timerfd_create().
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
static void on_alarm(int sig) { (void)sig; /* nothing; just interrupt */ }
int main(void) {
struct sigaction sa = {0};
sa.sa_handler = on_alarm;
sigemptyset(&sa.sa_mask);
sigaction(SIGALRM, &sa, NULL);
char buf[32];
alarm(3); /* 3-second budget */
ssize_t n = read(STDIN_FILENO, buf, sizeof buf);
alarm(0); /* cancel */
if (n < 0 && errno == EINTR) {
printf("read timed out\n");
return 1;
}
printf("got %zd bytes\n", n);
return 0;
}
alarm(0) on the success path. A stale alarm fires later and surprises you.alarm(n) schedules SIGALRM for n seconds later. Default action is terminate, so install a handler first. Cancel with alarm(0).