Linux System Programming · beginner · ~8 min
Use alarm() to time-out a blocking operation.
alarm() doesalarm(n) asks the kernel to send the signal SIGALRM to your process after n seconds. A signal is an asynchronous notification the kernel delivers to a process.
Some system calls block — they pause your program until they have something to return. Examples are read(), accept(), and connect().
alarm() lets such a call give up after a deadline. The pattern is:
SIGALRM handler that does nothing useful (or just sets a flag).alarm(n) to start the countdown.When SIGALRM fires, it interrupts the blocked call. The call then returns -1 and sets errno to EINTR ("interrupted system call"). That is your signal that the timeout was hit.
alarm(0) cancels a pending alarm.setitimer(), or — on 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;
}
SIGALRM handler. The default action for SIGALRM is to terminate the process. Without a handler, the timeout kills your program instead of just interrupting the read().alarm(0) on the success path. A leftover alarm fires later and surprises you at an unexpected moment.alarm(n) schedules SIGALRM to arrive n seconds from now.SIGALRM is to terminate the process, so install a handler first.-1 with errno == EINTR.alarm(0).