linux-sysprog · intermediate · ~30 min

Map poll() events to per-fd readiness flags

Bit-masked event interpretation.

Challenge

After a poll() call returns, decide which file descriptors have data or an error waiting. This is pure bit-flag interpretation on a fixed revents array — no real poll() is called.

Task

Implement void poll_check_ready(short *revents, int n, int *out_ready) that marks which descriptors are "ready" based on their returned event bits.

Input

  • revents, n: the per-descriptor returned-events bitmask array, as poll() would fill it. The relevant bits are:
#define POLLIN  0x0001   /* data to read */
#define POLLOUT 0x0004   /* writable */
#define POLLERR 0x0008   /* error */
#define POLLHUP 0x0010   /* peer hung up */
  • out_ready: output array of length n.

Output

Sets out_ready[i] = 1 if revents[i] has any of POLLIN, POLLERR, or POLLHUP set, otherwise 0. (POLLOUT alone does not count as ready here.)

Example

revents = { POLLIN, POLLOUT, POLLERR, POLLHUP|POLLIN, 0 }
poll_check_ready(revents, 5, out)
   ->   out = [1, 0, 1, 1, 0]

Edge cases

  • An all-zero revents gives an all-zero out_ready.
  • POLLOUT by itself maps to 0.

Why this matters

poll() is the modern, portable cousin of select. Knowing how to translate the event flags is the inner loop of any event-driven server.

Input format

An array revents of n returned-event bitmasks, plus an output array out_ready of length n. Bit constants POLLIN/POLLOUT/POLLERR/POLLHUP are given.

Output format

out_ready[i] = 1 if revents[i] has any of POLLIN|POLLERR|POLLHUP set, else 0.

Constraints

Test with & against (POLLIN|POLLERR|POLLHUP). POLLOUT alone is not 'ready'.

Starter code

#define POLLIN  0x0001
#define POLLOUT 0x0004
#define POLLERR 0x0008
#define POLLHUP 0x0010
void poll_check_ready(short *revents, int n, int *out_ready) { /* TODO */ }

Common mistakes

Treating POLLOUT as a 'something happened' bit (it is, but for write-readiness, not read-side); using == instead of & for the bit check; missing POLLHUP (a closed peer often only signals via POLLHUP).

Edge cases to handle

All-zero revents -> all-zero out_ready. POLLOUT alone -> not ready by this rule.

Complexity

O(n).

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