
Recall first from POSIX timers and timerfd
- timerfd turns a timer into a readable file descriptor, so one epoll loop waits on timers and I/O together
- The uint64_t read from a timerfd counts expirations since the last read, so missed ticks accumulate instead of disappearing
- A POSIX timer keeps at most one signal pending, whatever the signal; extra expirations become an overrun count that timer_getoverrun reports
Timeouts on blocking calls
1 min readYou now have timers that fire. This lesson applies time to blocking I/O with timeouts, and warns about the clock jumps and NTP steps that break naive code.
A blocking call is one that can sleep until its event arrives: a recv with no data, a read on a pipe whose writer is silent, a select waiting for anything. A timeout bounds that wait. In user space there are four workable ways to add one: a socket receive timeout, a poll/select/epoll timeout, a signal timer, and the timerfd you met in the last lesson.
SO_RCVTIMEO is set with setsockopt and a struct timeval:
struct timeval tv = { .tv_sec = 2, .tv_usec = 0 };
if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv) < 0)
perror("setsockopt");
After this, a blocking recv on fd returns -1 with errno EAGAIN when two seconds pass with no data. EAGAIN is the same value as EWOULDBLOCK on Linux. Three facts matter. First, the timeout is relative and per call: it starts fresh on every recv, so a loop of ten recv calls can consume up to twenty seconds, not two. Second, it is a property of the socket, so it stays in force until you change it; a zero timeval disables it. Third, it covers receive operations (recv, recvfrom, recvmsg, and read on the socket) and, on Linux, accept; it does not time connect, which follows SO_SNDTIMEO instead. The kernel measures it with its own monotonic tick counter, so a wall-clock change does not stretch or shorten the wait. SO_RCVTIMEO is documented in socket(7), not in the getsockopt page.
select, poll and epoll_wait all take a timeout directly. select takes a struct timeval pointer; a null pointer waits forever. poll and epoll_wait take an int in milliseconds; -1 waits forever and 0 polls once and returns at once. These are relative waits too, and on Linux they are driven by monotonic hrtimers, so they are also immune to wall-clock steps. The trap is signals: when a signal interrupts the wait, the call returns -1 with EINTR. select may write the remaining time back into your timeval on Linux, but poll and epoll_wait never update theirs, and POSIX does not guarantee even select does. After EINTR you therefore cannot trust any leftover value: you must recompute the remaining time against a deadline of your own, which is exactly what the last section builds.
alarm(2) and setitimer(2) are the older signal-based route. alarm(n) asks for SIGALRM after n seconds; setitimer(ITIMER_REAL, ...) does the same with microsecond precision and an optional repeating interval, and adds ITIMER_VIRTUAL (CPU time in user mode) and ITIMER_PROF (user plus system CPU time). The classic pattern installs a SIGALRM handler, arms the timer, makes the blocking call, and lets the signal interrupt it with EINTR. Four pitfalls make this worth avoiding. There is one such real-time timer per process, so arming a second timeout for a second call silently replaces the first; two pending operations cannot get independent timeouts. There is a race: if the signal is delivered after alarm() returns but before the blocking call begins, the handler runs, the timer is consumed, and the call then sleeps forever with nothing left to interrupt it. A handler runs asynchronously and may only call async-signal-safe functions, and longjmp out of a handler to abandon a half-finished read is unsafe because locks and buffers are left inconsistent. Finally, if the call already moved data before EINTR, that partial progress must be accounted for, not just retried. pselect and ppoll close the race by unmasking the signal and starting the wait atomically, but the handler limits remain.
timerfd removes the signal entirely: timerfd_create(CLOCK_MONOTONIC) plus timerfd_settime gives a file descriptor that becomes readable at the deadline and drops straight into poll or epoll. That is the mechanism the rest of this lesson builds on.
Monotonic and realtime clocks
3 min readLinux exposes several clocks through clock_gettime(2). Two matter here, plus one for boards that sleep.
CLOCK_REALTIME is the wall clock. It counts seconds since the Unix epoch (1970-01-01 UTC) and is what date and logs show. It can be set. NTP can step it, including backward, with clock_settime or adjtimex ADJ_SETOFFSET, and a user can change the date by hand. A stepped clock breaks any code that assumed time only moves forward: a deadline recorded as "now + 5 seconds" of realtime means a different amount of real waiting once the clock has jumped.
CLOCK_MONOTONIC counts time from an unspecified fixed point (in practice boot) and only moves forward. It cannot be set, and an NTP step does not touch it. NTP may still apply a tiny, bounded frequency correction to it, but it never steps backward or forward. This is the clock for intervals and deadlines. CLOCK_MONOTONIC_RAW is the underlying hardware counter with no NTP frequency correction at all; you rarely need it.
There is a difference between an NTP step and a slew. A step moves the clock instantly; a slew (adjtime) changes the rate for a while so the clock drifts gradually toward the right time, avoiding backward motion. Both affect CLOCK_REALTIME. Neither moves CLOCK_MONOTONIC backward, so a timeout built on the monotonic clock is safe either way.
Daylight saving time does not step the clock at all. The kernel keeps UTC, and DST is an offset that lives in the timezone database (tzdata), applied only when you convert to local time with localtime, mktime or strftime. CLOCK_REALTIME keeps counting UTC seconds straight through a DST change. DST only bites formatting and local-time arithmetic: subtracting two local times that straddle the change yields a 23- or 25-hour "day", and naive "add 24 local hours" can skip or repeat an hour. The rule: store UTC, measure with a monotonic clock, and convert to local time only at the edge where you print.
Suspend matters on a board. CLOCK_MONOTONIC stops while the system is suspended; it measures time the system has actually been running. CLOCK_BOOTTIME behaves like CLOCK_MONOTONIC but keeps counting across suspend. A Raspberry Pi or BeagleBone that sleeps and wakes should time "how long since the sensor was read" with CLOCK_BOOTTIME when the answer must include the sleep.
The failure to avoid is computing a timeout by reading CLOCK_REALTIME, adding five seconds, and later polling until CLOCK_REALTIME passes the target. If NTP steps the clock backward the wait extends; if forward the code times out early or spins. Compute the deadline on a monotonic clock instead.
A deadline loop for a network client
2 min readThe lab asks you to write a network client that reads a fixed number of bytes but gives up after a bounded time, surviving partial reads. A single recv on a TCP stream rarely returns exactly the bytes you asked for: it may return fewer, so you must loop. A single SO_RCVTIMEO bounds one recv, not the whole message. The right shape is a monotonic deadline plus a poll loop, in three parts: record the deadline once on CLOCK_MONOTONIC, compute the time left before each wait, then wait for readability with that remaining time and read what is there.
/* Needs -D_GNU_SOURCE: with -std=c17 glibc hides POSIX declarations. */
static struct timespec mono_now(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts;
}
static long ms_left(struct timespec deadline)
{
struct timespec now = mono_now();
long sec = deadline.tv_sec - now.tv_sec;
long nsec = deadline.tv_nsec - now.tv_nsec;
return sec * 1000 + nsec / 1000000;
}
/* Read exactly n bytes before deadline; handles partial reads and EINTR. */
static int read_exact(int fd, char *buf, size_t n, struct timespec deadline)
{
size_t got = 0;
while (got < n) {
long rem = ms_left(deadline);
if (rem <= 0) { errno = ETIMEDOUT; return -1; }
struct pollfd p = { .fd = fd, .events = POLLIN };
int pr = poll(&p, 1, (int)rem);
if (pr < 0) {
if (errno == EINTR) continue;
return -1;
}
if (pr == 0) continue; /* time is up: the rem check ends it */
ssize_t r = read(fd, buf + got, n - got);
if (r < 0) {
if (errno == EINTR) continue;
return -1;
}
if (r == 0) { errno = ECONNRESET; return -1; }
got += (size_t)r;
}
return 0;
}
Every iteration recomputes rem from the fixed deadline, so a signal interrupt (EINTR), an early poll return, or time spent inside read does not reset the budget: only the wait shrinks. Partial reads are handled because the loop keeps going while got is below n and read writes into buf + got.
Three details to get right in the lab. First, poll's timeout is an int of milliseconds; ms_left is fine against a near deadline, and if poll returns 0 the next ms_left check yields a non-positive value and the loop exits with ETIMEDOUT. The rem check sits first so a zero-length wait never falls through to read. Second, read returning 0 means the peer closed the stream, which is end-of-stream rather than a timeout: map it to a distinct error so the client can tell "peer hung up early" from "took too long". Third, connect can block for a long time and SO_RCVTIMEO does not cover it (SO_SNDTIMEO does, but only per call); to time a connect you make the socket non-blocking, call connect, poll for POLLOUT and check SO_ERROR, which is the challenge exercise.
The deadline clock must be monotonic (or CLOCK_BOOTTIME if the device suspends). Built on CLOCK_REALTIME, the same loop would hang past its timeout after a backward NTP step and fail instantly after a forward one. That is why this lesson pairs timeouts with clock discipline.
On glibc 2.39 every call here lives in libc (clock_gettime has not needed -lrt since glibc 2.17), so the lab's client links with a plain gcc command plus -D_GNU_SOURCE.
The next lesson leaves time for hardware: GPIO with libgpiod, where the same poll loops wait on pin events instead of socket data.
Key takeaways
- SO_RCVTIMEO, poll/select/epoll timeouts and a CLOCK_MONOTONIC timerfd all measure their waits with the kernel's monotonic time, so a wall-clock change does not stretch or shorten them.
- alarm() and setitimer() give one real-time timer per process, race with the blocking call, and are limited by async-signal-safety.
- CLOCK_REALTIME can step with NTP or a manual date change; CLOCK_MONOTONIC cannot, and a DST transition changes only local-time formatting, never the UTC or monotonic clock.
- A robust client fixes its deadline once on a monotonic clock and recomputes the remaining wait each loop iteration, handling partial reads and EINTR.
Reflect
- Explain to a colleague, in two sentences: set a receive timeout with SO_RCVTIMEO and explain which calls it covers.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pageclock_gettime(2): clock and time functions
- Man pagepoll(2): wait for some event on a file descriptor
- Man pagesetitimer(2): get and set interval timers
- Man pagesocket(7): socket interface
- Man pagetime(7): overview of time and timers
Official documentation first. Links checked when the lesson was published.