linux-sysprog · intermediate · ~30 min
Bit-masked event interpretation.
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.
Implement void poll_check_ready(short *revents, int n, int *out_ready) that marks which descriptors are "ready" based on their returned event bits.
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.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.)
revents = { POLLIN, POLLOUT, POLLERR, POLLHUP|POLLIN, 0 }
poll_check_ready(revents, 5, out)
-> out = [1, 0, 1, 1, 0]
revents gives an all-zero out_ready.POLLOUT by itself maps to 0.poll() is the modern, portable cousin of select. Knowing how to translate the event flags is the inner loop of any event-driven server.
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.
out_ready[i] = 1 if revents[i] has any of POLLIN|POLLERR|POLLHUP set, else 0.
Test with & against (POLLIN|POLLERR|POLLHUP). POLLOUT alone is not 'ready'.
#define POLLIN 0x0001
#define POLLOUT 0x0004
#define POLLERR 0x0008
#define POLLHUP 0x0010
void poll_check_ready(short *revents, int n, int *out_ready) { /* TODO */ }
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).
All-zero revents -> all-zero out_ready. POLLOUT alone -> not ready by this rule.
O(n).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.