networking · intermediate · ~15 min

Would the call have blocked?

Detect the would-block condition.

Challenge

Detect the would-block condition from a non-blocking socket call's result.

On a non-blocking socket, an operation that has no data ready returns -1 and sets errno to EAGAIN/EWOULDBLOCK.

Task

Implement int would_block(int rc, int err, int eagain).

Input

  • rc: the return code from the socket call.
  • err: the errno value after the call.
  • eagain: the value that represents EAGAIN/EWOULDBLOCK on this platform.

Output

Return 1 if rc < 0 and err == eagain, else 0.

Example

would_block(-1, 11, 11)  ->  1   (rc<0 and err==EAGAIN)
would_block(5,  0,  11)  ->  0   (call succeeded)
would_block(-1, 9,  11)  ->  0   (different errno)

Input format

rc: the call's return code; err: errno afterward; eagain: this platform's EAGAIN value.

Output format

1 if rc < 0 and err == eagain, else 0.

Constraints

Both conditions must hold: a failed return AND the EAGAIN errno.

Starter code

int would_block(int rc, int err, int eagain) {
    /* TODO */
    return 0;
}

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