networking · intermediate · ~15 min

Filter the fds reported as readable by epoll_wait

The dispatch-loop pattern; mask matching for the 'readable' flags.

Challenge

Define the bit constants and a struct just like epoll's:

#define EPOLLIN  0x001
#define EPOLLOUT 0x004
#define EPOLLERR 0x008
#define EPOLLHUP 0x010

typedef struct { int events; int fd; } evt_t;

Implement int filter_readable(const evt_t *in, int n, int *out_fds, int max). The function copies into out_fds[] every in[i].fd whose in[i].events has EPOLLIN OR EPOLLHUP OR EPOLLERR set (these are the three flags that indicate "you should read"). Returns the count copied (<= max).

Why this matters

When epoll_wait fills your events[] buffer, you walk it once and dispatch each fd. Getting the dispatch loop right — including masks for HUP/ERR — is the difference between a working server and a stuck one.

Input format

Array of {events, fd}.

Output format

Count + filled out_fds.

Constraints

Single pass; respect max.

Starter code

#define EPOLLIN  0x001
#define EPOLLOUT 0x004
#define EPOLLERR 0x008
#define EPOLLHUP 0x010
typedef struct { int events; int fd; } evt_t;
int filter_readable(const evt_t *in, int n, int *out_fds, int max) { /* TODO */ return 0; }

Common mistakes

Treating only EPOLLIN as 'readable' — HUP and ERR also need attention.

Edge cases to handle

Empty input, all-set, none-set, max smaller than matches.

Complexity

O(n).

Background lessons

Up next

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