networking · advanced · ~15 min

Connect deadline math

Compute the time remaining before a connect() deadline.

Challenge

A non-blocking connect() polls until it succeeds or a deadline passes. Implement the deadline arithmetic:

long deadline_remaining_ms(long start_ms, long timeout_ms, long now_ms);

The deadline is start_ms + timeout_ms. Return the milliseconds remaining, or −1 once now_ms has reached or passed the deadline.

Input format

Three millisecond timestamps.

Output format

Milliseconds remaining, or −1 past the deadline.

Constraints

The check is now_ms >= deadline → -1. A now_ms before start_ms yields more than timeout_ms remaining.

Starter code

#include <stddef.h>
/* A connect started at start_ms with a timeout_ms budget. Given the current
   clock now_ms, return the milliseconds remaining before the deadline
   (start_ms+timeout_ms). Return 0 if none are left but the deadline is not yet
   passed... return -1 once now_ms has reached or passed the deadline. */
long deadline_remaining_ms(long start_ms, long timeout_ms, long now_ms){ (void)start_ms;(void)timeout_ms;(void)now_ms; return -1; }

Common mistakes

Using > instead of >= at the deadline; returning 0 instead of −1 when expired; integer overflow with int (use long).

Edge cases to handle

At exactly the deadline the result is −1 (not 0); a zero timeout is immediately expired.

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