linux-sysprog · intermediate · ~10 min

Time-out a blocking read with alarm()

Use alarm() + SIGALRM to bound a read.

Challenge

Implement int read_with_timeout(int fd, char *buf, int cap, int seconds).

Install a SIGALRM handler (so the default 'terminate' action doesn't kill you), call alarm(seconds), then read(fd, buf, cap). Cancel the alarm with alarm(0) afterwards. Return:

  • the number of bytes read on success
  • -1 if the read was interrupted by the alarm (errno == EINTR)

Why this matters

alarm() + a no-op handler is the simplest way to put a time budget on a blocking syscall.

Starter code

#include <signal.h>
#include <unistd.h>
#include <errno.h>
int read_with_timeout(int fd, char *buf, int cap, int seconds) {
    /* TODO */
    return -1;
}

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.