Linux System Programming · beginner · ~8 min

alarm() — schedule a SIGALRM in N seconds

Use alarm() to time-out a blocking operation.

Lesson

What alarm() does

alarm(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.

The classic use: timing out a blocking call

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:

  1. Install a SIGALRM handler that does nothing useful (or just sets a flag).
  2. Call alarm(n) to start the countdown.
  3. Issue the blocking system call.

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.

Canceling and finer timers

  • alarm(0) cancels a pending alarm.
  • For sub-second or repeating timers, use setitimer(), or — on modern Linux — timerfd_create().

Code examples

#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;
}

Common mistakes

  • Forgetting to install a 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().
  • Forgetting alarm(0) on the success path. A leftover alarm fires later and surprises you at an unexpected moment.

Summary

  • alarm(n) schedules SIGALRM to arrive n seconds from now.
  • The default action for SIGALRM is to terminate the process, so install a handler first.
  • When the alarm interrupts a blocking call, that call returns -1 with errno == EINTR.
  • Cancel a pending alarm with alarm(0).

Practice with these exercises