linux-sysprog · intermediate · ~10 min
Use alarm() + SIGALRM to bound a read.
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:
-1 if the read was interrupted by the alarm (errno == EINTR)alarm() + a no-op handler is the simplest way to put a time budget on a blocking syscall.
#include <signal.h>
#include <unistd.h>
#include <errno.h>
int read_with_timeout(int fd, char *buf, int cap, int seconds) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.