networking · advanced · ~40 min
Bit-packed sets; bitwise add/remove with mask.
Implement a fixed-capacity FD bitmap:
typedef struct fdset fdset_t;
fdset_t *fdset_create(int max_fd); /* tracks FDs 0..max_fd inclusive */
void fdset_add(fdset_t *s, int fd);
void fdset_remove(fdset_t *s, int fd);
int fdset_contains(fdset_t *s, int fd);
int fdset_count(fdset_t *s);
void fdset_destroy(fdset_t *s);
Use 32 FDs per uint32_t. fd_set_add on an out-of-range fd is a no-op.
select(2) uses an fd_set — a bitmap of file descriptor numbers. Implementing it teaches bitmap math and why epoll superseded select for high-FD-count servers.
max_fd >= 0; fd is int.
See API.
Use (max_fd / 32) + 1 words. No loops in add/remove/contains (just bit math).
typedef struct fdset fdset_t;
fdset_t *fdset_create(int max_fd);
void fdset_add(fdset_t *s, int fd);
void fdset_remove(fdset_t *s, int fd);
int fdset_contains(fdset_t *s, int fd);
int fdset_count(fdset_t *s);
void fdset_destroy(fdset_t *s);
Indexing past the bitmap on a large fd; using a signed type so the high bit shifts wrong; double-counting in count via a manual popcount with mismatched mask.
add same fd twice — still counted once. remove of absent fd — no-op.
O(1) add/remove/contains. O(words) count.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.