linux-sysprog · beginner · ~10 min

One-shot timer: 'is now past the fire time?'

Absolute-time scheduling — the core of timerfd, setitimer, every cron alternative.

Challenge

Implement int timer_due(long now_ms, long fire_at_ms) returning 1 if fire_at_ms <= now_ms (i.e. the timer has fired), 0 otherwise.

Then implement long timer_remaining_ms(long now_ms, long fire_at_ms) returning how many ms remain (0 if the timer is due).

Why this matters

timerfd lets you turn a timer into a file descriptor. The core idea: 'absolute moment X in the future'. Once you internalise that, the whole API makes sense.

Input format

Current ms + fire-at ms.

Output format

0/1 (due?) and ms remaining.

Constraints

No real syscalls.

Starter code

int timer_due(long now_ms, long fire_at_ms) { /* TODO */ return 0; }
long timer_remaining_ms(long now_ms, long fire_at_ms) { /* TODO */ return 0; }

Common mistakes

Using subtraction without checking for negative — fire - now may go negative once due.

Edge cases to handle

fire_at_ms == now_ms (just due). Far-future timer. Already-past timer.

Complexity

O(1).

Background lessons

Up next

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