Lab 1: Edge-Triggered Epoll Pipe & Eventfd Reactor
Transition file descriptors into nonblocking mode (O_NONBLOCK), compare O(N) select() and poll() readiness scans, and build scalable O(1)-ready epoll_create1/EPOLLET/eventfd event loops.
Prerequisites in this module
What ./check.sh verifies
- Builds with -std=c11 -Wall -Wextra and no warnings.
- Archives reactor.o into libreactor.a and links epoll_reactor.
- Drains 25-frame bursts across 4 EPOLLET pipes until EAGAIN.
- Drains 40-frame bursts with deterministic XOR digest 0xf728e538.
step 1/15 · inspect starter files and specification
Single-threaded telemetry gateways and log collectors routinely ingest bursts across dozens of local worker pipes while listening for an asynchronous supervisor shutdown trigger. If a developer leaves pipes in default blocking mode, a single 19-byte chunk read on an drained stream stalls every sibling channel; if they enable EPOLLET (Edge-Triggered epoll) without looping read() until -1 (errno == EAGAIN), a 64-byte burst leaves 45 bytes stranded silently inside the kernel pipe ring buffer forever! In this studio lab, you build libreactor.a and epoll_reactor to prove lossless EPOLLET burst draining and 8-byte eventfd shutdown signaling.
learner@ksa:~/gl-c03/lab-m01ls -lastarter/Makefilestarter/epoll_reactor.cstarter/reactor.cstarter/reactor.hlearner@ksa:~/gl-c03/lab-m01starter: starter/Makefile
learner@ksa:~/gl-c03/lab-m01$ bat starter/Makefile File: starter/Makefile CC ?= gcc CFLAGS := -O0 -pthread # BUGGY STARTER: # 1. Missing -std=c11 -Wall -Wextra -Werror # 2. Does not archive reactor.o into libreactor.a via ar rcs all: epoll_reactor epoll_reactor: reactor.c epoll_reactor.c $(CC) $(CFLAGS) reactor.c epoll_reactor.c -o epoll_reactor clean: rm -f *.o epoll_reactorstarter: starter/epoll_reactor.c
learner@ksa:~/gl-c03/lab-m01$ bat starter/epoll_reactor.c File: starter/epoll_reactor.c #include "reactor.h" #include <stdio.h> #include <unistd.h> int main(void) { int rd[REACTOR_CHANNELS], wr[REACTOR_CHANNELS], evfd = -1; if (reactor_open_channels(rd, wr, &evfd) == -1) { return 1; } for (int i = 0; i < REACTOR_CHANNELS; i++) { close(wr[i]); } struct reactor_stats st; reactor_run_loop(rd, evfd, &st); printf("channels=%u frames=%u bytes=%zu\n", st.channels_eof, st.total_frames, st.total_bytes); return 0; }starter: starter/reactor.c
learner@ksa:~/gl-c03/lab-m01$ bat starter/reactor.c File: starter/reactor.c #define _GNU_SOURCE #include "reactor.h" #include <string.h> #include <sys/epoll.h> #include <sys/eventfd.h> #include <unistd.h> /* BUGGY STARTER: * 1. Opens blocking pipes via pipe() instead of pipe2(..., O_NONBLOCK | O_CLOEXEC)! * 2. Performs only ONE 19-byte read() per EPOLLET wakeup instead of draining until EAGAIN! * 3. Never registers or reads the eventfd shutdown descriptor! */ int reactor_open_channels(int rd_fds[REACTOR_CHANNELS], int wr_fds[REACTOR_CHANNELS], int *evfd_out) { for (int i = 0; i < REACTOR_CHANNELS; i++) { int pair[2]; if (pipe(pair) == -1) { return -1; } rd_fds[i] = pair[0]; wr_fds[i] = pair[1]; } *evfd_out = eventfd(0U, 0); return (*evfd_out == -1) ? -1 : 0; } int reactor_run_loop(const int rd_fds[REACTOR_CHANNELS], int evfd, struct reactor_stats *out) { (void)evfd; memset(out, 0, sizeof(*out)); int epfd = epoll_create1(0); for (uint32_t i = 0U; i < (uint32_t)REACTOR_CHANNELS; i++) { struct epoll_event ev = {.events = EPOLLIN | EPOLLET, .data.u32 = i}; epoll_ctl(epfd, EPOLL_CTL_ADD, rd_fds[i], &ev); } struct epoll_event events[4]; int nready = epoll_wait(epfd, events, 4, 50); for (int i = 0; i < nready; i++) { uint8_t chunk[19]; ssize_t r = read(rd_fds[events[i].data.u32], chunk, sizeof(chunk)); if (r > 0) { out->total_bytes += (size_t)r; } } close(epfd); return 0; }starter: starter/reactor.h
learner@ksa:~/gl-c03/lab-m01$ bat starter/reactor.h File: starter/reactor.h #ifndef KSA_REACTOR_H #define KSA_REACTOR_H #include <stddef.h> #include <stdint.h> #define REACTOR_CHANNELS 4 #define REACTOR_FRAME_BYTES 16U struct reactor_stats { uint32_t channels_eof; uint32_t total_frames; size_t total_bytes; uint32_t xor_sum; uint64_t stop_counter; uint32_t eagain_drains; }; int reactor_open_channels(int rd_fds[REACTOR_CHANNELS], int wr_fds[REACTOR_CHANNELS], int *evfd_out); int reactor_run_loop(const int rd_fds[REACTOR_CHANNELS], int evfd, struct reactor_stats *out); #endifstep 2/15 · 2. learning objectives
- Configure
4nonblockingpipe2(..., O_NONBLOCK | O_CLOEXEC)channels and1eventfd(0U, EFD_NONBLOCK | EFD_CLOEXEC)descriptor with leak-free error rollback. - Archive
reactor.ointo static librarylibreactor.a(ar rcs) and link./epoll_reactorcleanly under-std=c11 -Wall -Wextra -Werror -O2 -g -pthread. - Implement an
epoll_create1(EPOLL_CLOEXEC)reactor registered withEPOLLIN | EPOLLETthat drains19-byte sub-chunks in afor (;;)loop untilerrno == EAGAINand deregisters closed channels onEOF(EPOLL_CTL_DEL). - Verify deterministic
16-byte frame XOR checksums (0x2a11eb87at25frames/ch,0xf728e538at40frames/ch) and8-byteuint64_teventfdshutdown observation.
step 3/15 · 3. environment requirements
- Execution Mode: Unprivileged Linux user space (
Linux 6.12 LTSor newer host kernel; portable to32-bitARMv7Cortex-A7target rootfs). - Kernel Subsystems Used:
fs/pipe.c(pipe2),fs/eventpoll.c(epoll_create1,epoll_ctl,epoll_waitwithEPOLLET), andfs/eventfd.c(eventfd2). - Concurrency Contract:
reactor_run_loop()runs on a single event-loop thread;epoll_reactor.cspawns one producerpthreadstrictly to inject multi-frame pipe bursts and write theeventfdcounter.
step 4/15 · 4. required software & hardware
- Toolchain: GNU
gcc(ISO C11), GNUar(binutils), GNUmake, POSIX shell (sh), andstrace(optional syscall inspection). - Hardware: Standard
x86_64orARMv7Linux host (>= 64 MiBfree RAM; zero external board hardware or root privileges required).
step 5/15 · 5. complete executable commands
Run every command from course_creator/courses/linux-c-ipc-net/labs/lab_m01_epoll_reactor:
learner@ksa:~/gl-c03/lab-m01$ bat script.sh File: script.sh # 1. Inspect how the unfixed starter fails TAP checks 2..5 (Predict phase): # Why: Confirms the test harness catches missing libreactor.a, stranded EPOLLET bytes, and ignored eventfd. make -C starter clean && make -C starter && ./starter/epoll_reactor # 2. Build the multi-file C11 static archive and CLI in files/ (Build phase): # Why: Compiles reactor.o and epoll_reactor.o with -Werror, packs libreactor.a, and links epoll_reactor. make -C files clean && make -C files ar t files/libreactor.a # 3. Execute deterministic 25-frame and 40-frame 4-channel burst runs: # Why: Verifies 4 * 25 * 16 = 1600 bytes (0x2a11eb87) and 4 * 40 * 16 = 2560 bytes (0xf728e538). ./files/epoll_reactor 25 ./files/epoll_reactor 40 # 4. Run the automated 5-point TAP v13 grading script (Verify phase): # Why: Validates compiler flags, archive contents, both burst digests, and clean exit status 0. sh check.sh # 5. Optional syscall verification with strace: # Why: Confirms pipe2(O_NONBLOCK|O_CLOEXEC), eventfd2, EPOLLET registration, and -1 EAGAIN drains. strace -e trace=pipe2,eventfd2,epoll_create1,epoll_ctl,epoll_wait ./files/epoll_reactor 25step 6/15 · 6. annotated source code (`starter/` defects vs `files/` solution)
Starter Defects (starter/reactor.c)
pipe(pair)andeventfd(0U, 0)omitO_NONBLOCK | O_CLOEXECandEFD_NONBLOCK | EFD_CLOEXEC: a loop drainingEPOLLETon a blocking descriptor deadlocks on the finalread()!epoll_wait(epfd, events, 4, 50)runs once instead of looping until all4channels hitEOFandstop_counter > 0, and reads only one19-byte chunk (ssize_t r = read(..., chunk, 19);) per wakeup, stranding the remaining45bytes of every64-byte (4-frame) batch!
Key Solution Pattern (files/reactor.c)
learner@ksa:~/gl-c03/lab-m01$ bat example.c File: example.c /* Inside reactor_run_loop(): drain each EPOLLET pipe in 19-byte chunks until EAGAIN or EOF */ for (;;) { uint8_t chunk[19]; ssize_t r = read(fd, chunk, sizeof(chunk)); if (r > 0) { /* Accumulate into per-channel 16-byte frame buffer and fold 32-bit words into xor_sum */ out->total_bytes += (size_t)r; /* ... frame extraction ... */ } else if (r == 0) { /* Writer closed pipe: deregister fd from epoll rbtree and count EOF */ (void)epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL); out->channels_eof++; break; } else if (errno == EINTR) { continue; } else if (errno == EAGAIN || errno == EWOULDBLOCK) { out->eagain_drains++; /* Mandatory EPOLLET completion invariant! */ break; } else { return -1; } }step 7/15 · 7. expected output
CLI Output
learner@ksa:~/gl-c03/lab-m01$ bat listing.txt File: listing.txt $ ./files/epoll_reactor 25 channels=4 frames=100 bytes=1600 xor_sum=0x2a11eb87 stop_evfd=1 $ ./files/epoll_reactor 40 channels=4 frames=160 bytes=2560 xor_sum=0xf728e538 stop_evfd=1Automated sh check.sh TAP 13 Output
learner@ksa:~/gl-c03/lab-m01$ bat listing.txt File: listing.txt TAP version 13 1..5 ok 1 - builds with -std=c11 -Wall -Wextra and no warnings ok 2 - archives reactor.o into libreactor.a and links epoll_reactor ok 3 - drains 25-frame bursts across 4 EPOLLET pipes until EAGAIN ok 4 - drains 40-frame bursts with deterministic XOR digest 0xf728e538 ok 5 - observes 8-byte eventfd shutdown counter and deregisters EOF channels # pass 5/5step 8/15 · 8. explanation of observed behavior
- Why a
19-byte read buffer works cleanly for16-byte frames: Prime chunk size19deliberately cuts across16-byte frame boundaries (19 = 16 + 3, leaving13bytes needed for Frame 2!). Maintaining a16-byte per-channel staging buffer insidereactor.cproves that stream reassembly is independent of kernel read chunk sizes. - Why
EPOLLETloses zero bytes here: Becauseproducer_mainwrites4-frame (64-byte) bursts andreactor_run_looploopsread(..., 19)(19 + 19 + 19 + 7 = 64, followed by-1 EAGAIN),ep_poll_callbackre-arms cleanly for the next burst. - Why
eventfdrequires8bytes:fs/eventfd.cmaintains a64-bit kernel counter; readingsizeof(uint64_t)(8bytes) atomically harvests the accumulated count and resets the kernel counter to0.
step 9/15 · 9. experiment variations
- Near transfer (Chunk-Size Sensitivity): Change
uint8_t chunk[19]infiles/reactor.ctochunk[7]and thenchunk[256], rebuild, and printst.eagain_drains. Verify thatframes=100,bytes=1600, andxor_sum=0x2a11eb87remain100%identical whileread()syscall count scales inversely with chunk size! - Far transfer (
timerfdHeartbeat Channel): Register atimerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC)firing every2 msas.data.u32 = 99Uonepfdand count periodic ticks alongside pipe bursts without adding threads.
step 10/15 · 10. performance measurements
Measured using clock_gettime(CLOCK_MONOTONIC, ...) (5 warmup runs discarded, N = 35 measured runs, compiled with -O2) driving 1,000 frames (16,000 bytes across 4 EPOLLET pipes + eventfd teardown per run):
| Metric | Host Linux (x86_64, -O2) | Target ARMv7 Cortex-A7 (~800 MHz..1 GHz Estimate) |
|---|---|---|
| Workload | 1,000 frames (16 KiB) + eventfd | Same binary contract (32-bit arm-linux-gnueabihf) |
p50 Latency | 808.16 us | ~3,800 .. 6,500 us (higher syscall + L2 cache cost) |
p95 Latency | 947.71 us | ~4,900 .. 8,000 us |
p99 Latency | 1032.64 us | ~5,800 .. 9,500 us |
Throughput (p50) | 1,237,373 frames/s | ~150,000 .. 260,000 frames/s |
step 11/15 · 11. troubleshooting
| Symptom | Root Cause | Fix | ||
|---|---|---|---|---|
./epoll_reactor 25 hangs indefinitely | Pipes opened without O_NONBLOCK (pipe() instead of pipe2(..., O_NONBLOCK)) block on the final EPOLLET drain iteration | Open all 4 pairs via `pipe2(pair, O_NONBLOCK \ | O_CLOEXEC) and eventfd with EFD_NONBLOCK \ | EFD_CLOEXEC` |
bytes=76 instead of bytes=1600 before hang/timeout | Handler executed if (1 read() per epoll_wait event) instead of for (;;) draining to EAGAIN | Loop read() until -1 (`errno == EAGAIN \ | \ | errno == EWOULDBLOCK`) |
read(evfd, &cnt, 4) returns -1 (EINVAL) | eventfd rejects buffers smaller than 8 bytes (sizeof(uint64_t)) | Always pass a uint64_t (8-byte) variable to read(evfd, &val, sizeof(val)) | ||
check.sh fails test 2 (libreactor.a missing) | Makefile linked reactor.o directly without building libreactor.a | Add libreactor.a: reactor.o -> ar rcs $@ $^ in files/Makefile |
step 12/15 · 12. guided questions
- Why must
reactor_run_loop()trackchannels_eof == 4in addition tostop_counter > 0before breaking out of theepoll_wait()loop?
- *Hint 1:* When the producer thread writes
4pipe bursts, closeswr[0..3], and immediately writes1toevfd, which descriptor doesepoll_wait()return first insideevents[]? - *Hint 2:* What happens to unread bytes still sitting inside
rd[2]andrd[3]if the reactor exits the momentevents[0]happens to beevfd?
- Why do we call
epoll_ctl(epfd, EPOLL_CTL_DEL, fd, NULL)(orclose(fd)when owning the descriptor) as soon asread()returns0(EOF)?
- *Hint 1:* How does
pipe_poll()report readiness when all write ends of a pipe are closed? - *Hint 2:* Under level-triggered mode (or if another event triggers), what happens on an open pipe read end at
EOF(POLLHUP) if left registered?
step 13/15 · 13. independent challenges
- Multi-Producer
eventfdBatch Accounting: Spawn4independent producer threads (one per pipe), have each write1ULLto the sharedevfdupon completion, and verifystop_counteraccumulates to4ULLwhetherepoll_wait()wakes1,2, or4times. - Dynamic
EPOLLONESHOTWorker Dispatch: Extendlibreactor.aso two consumer threads shareepfdsafely by registering pipes withEPOLLIN | EPOLLET | EPOLLONESHOTand re-arming viaepoll_ctl(EPOLL_CTL_MOD)after eachEAGAINdrain.
step 14/15 · 14. solutions & explanations
- Guided Question 1:
epoll_wait()returns ready descriptors in ready-list (rdllist) insertion order; ifevfdis processed atevents[0]and breaks the outer loop immediately, pipe bytes still queued inrd[0..3]are abandoned! Waiting untilchannels_eof == REACTOR_CHANNELS && stop_counter > 0guarantees100%stream drain before shutdown. - Guided Question 2: Once all pipe writers close,
pipe_pollassertsEPOLLHUPpermanently. Deregistering viaEPOLL_CTL_DELimmediately onread() == 0removes the deadepitemfromep->rbrand prevents repeatedEOFwakeups. - Challenge Verification: In Challenge 1,
fs/eventfd.cuses a spinlock-guarded64-bit kernel addition (ctx->count += val), sosum(reads) == 4ULLis invariant across scheduling interleavings; in Challenge 2,EPOLLONESHOTprevents two threads from slicing19-byte chunks out of the same16-byte frame concurrently.
step 15/15 · run verification and inspect output
Run the verification command and confirm the output matches the expected contract.
learner@ksa:~/gl-c03/lab-m01./files/epoll_reactor 25learner@ksa:~/gl-c03/lab-m01channels=4 frames=100 bytes=1600 xor_sum=0x2a11eb87 stop_evfd=1Progressive hints & solution
hint 1
Compare starter/Makefile against the module lessons. Focus first on: Builds with -std=c11 -Wall -Wextra and no warnings.
hint 2
Compile with -std=c11 -Wall -Wextra -Werror, check every system-call return value before touching output buffers, and verify cleanup on error paths.
solution
warning: Reveal the reference solution files? Running ./check.sh against your own attempt first builds stronger retention.
solution: files/Makefile
learner@ksa:~/gl-c03/lab-m01$ bat files/Makefile File: files/Makefile CC ?= gcc AR ?= ar CFLAGS := -std=c11 -Wall -Wextra -Werror -O2 -g -pthread .PHONY: all clean all: libreactor.a epoll_reactor reactor.o: reactor.c reactor.h $(CC) $(CFLAGS) -DREACTOR_LIBRARY_BUILD -c reactor.c -o reactor.o libreactor.a: reactor.o $(AR) rcs libreactor.a reactor.o epoll_reactor.o: epoll_reactor.c reactor.h $(CC) $(CFLAGS) -c epoll_reactor.c -o epoll_reactor.o epoll_reactor: epoll_reactor.o libreactor.a $(CC) $(CFLAGS) epoll_reactor.o libreactor.a -o epoll_reactor clean: rm -f *.o libreactor.a epoll_reactorsolution: files/epoll_reactor.c
learner@ksa:~/gl-c03/lab-m01$ bat files/epoll_reactor.c File: files/epoll_reactor.c #define _GNU_SOURCE #include "reactor.h" #include <errno.h> #include <poll.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> struct producer_ctx { int wr_fds[REACTOR_CHANNELS]; int evfd; uint32_t frames_per_ch; int err; }; static int write_all_nonblock(int fd, const uint8_t *buf, size_t len) { size_t off = 0U; while (off < len) { ssize_t w = write(fd, buf + off, len - off); if (w > 0) { off += (size_t)w; } else if (w == -1 && errno == EINTR) { continue; } else if (w == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { struct pollfd pfd = {.fd = fd, .events = POLLOUT, .revents = 0}; (void)poll(&pfd, 1U, 100); } else { return -1; } } return 0; } static void *producer_main(void *arg) { struct producer_ctx *ctx = (struct producer_ctx *)arg; uint8_t batch[REACTOR_FRAME_BYTES * 4U]; uint32_t seq = 0U; while (seq < ctx->frames_per_ch) { uint32_t count = ctx->frames_per_ch - seq; if (count > 4U) { count = 4U; } for (uint32_t ch = 0U; ch < (uint32_t)REACTOR_CHANNELS; ch++) { for (uint32_t k = 0U; k < count; k++) { uint32_t s = seq + k; uint32_t w0 = 0xA500U | ch; uint32_t w1 = s; uint32_t w2 = (ch + 1U) * 257U + s; uint32_t w3 = w0 ^ w1 ^ w2 ^ ((1U << ch) * 0x9E3779B1U + s * 0x85EBCA6BU); size_t base = (size_t)k * REACTOR_FRAME_BYTES; memcpy(batch + base + 0U, &w0, 4U); memcpy(batch + base + 4U, &w1, 4U); memcpy(batch + base + 8U, &w2, 4U); memcpy(batch + base + 12U, &w3, 4U); } if (write_all_nonblock(ctx->wr_fds[ch], batch, (size_t)count * REACTOR_FRAME_BYTES) == -1) { ctx->err = 1; break; } } if (ctx->err) { break; } seq += count; } for (int i = 0; i < REACTOR_CHANNELS; i++) { (void)close(ctx->wr_fds[i]); } uint64_t done = 1U; if (write(ctx->evfd, &done, sizeof(done)) != (ssize_t)sizeof(done)) { ctx->err = 1; } return NULL; } int main(int argc, char *argv[]) { uint32_t frames_per_ch = 25U; if (argc >= 2) { char *end = NULL; errno = 0; unsigned long v = strtoul(argv[1], &end, 10); if (errno != 0 || end == argv[1] || *end != '\0' || v == 0UL || v > 10000UL) { fprintf(stderr, "Invalid frames_per_channel\n"); return EXIT_FAILURE; } frames_per_ch = (uint32_t)v; } int rd_fds[REACTOR_CHANNELS]; int wr_fds[REACTOR_CHANNELS]; int evfd = -1; if (reactor_open_channels(rd_fds, wr_fds, &evfd) == -1) { perror("reactor_open_channels"); return EXIT_FAILURE; } struct producer_ctx pctx; memset(&pctx, 0, sizeof(pctx)); memcpy(pctx.wr_fds, wr_fds, sizeof(wr_fds)); pctx.evfd = evfd; pctx.frames_per_ch = frames_per_ch; pthread_t prod_tid; if (pthread_create(&prod_tid, NULL, producer_main, &pctx) != 0) { return EXIT_FAILURE; } struct reactor_stats stats; int rc = reactor_run_loop(rd_fds, evfd, &stats); (void)pthread_join(prod_tid, NULL); for (int i = 0; i < REACTOR_CHANNELS; i++) { (void)close(rd_fds[i]); } (void)close(evfd); if (rc == -1 || pctx.err != 0) { return EXIT_FAILURE; } printf("channels=%u frames=%u bytes=%zu xor_sum=0x%08x stop_evfd=%d\n", stats.channels_eof, stats.total_frames, stats.total_bytes, stats.xor_sum, stats.stop_counter >= 1U); return EXIT_SUCCESS; }solution: files/reactor.c
learner@ksa:~/gl-c03/lab-m01$ bat files/reactor.c File: files/reactor.c #define _GNU_SOURCE #include "reactor.h" #include <errno.h> #include <fcntl.h> #include <string.h> #include <sys/epoll.h> #include <sys/eventfd.h> #include <unistd.h> int reactor_open_channels(int rd_fds[REACTOR_CHANNELS], int wr_fds[REACTOR_CHANNELS], int *evfd_out) { if (rd_fds == NULL || wr_fds == NULL || evfd_out == NULL) { errno = EINVAL; return -1; } for (int i = 0; i < REACTOR_CHANNELS; i++) { rd_fds[i] = -1; wr_fds[i] = -1; } *evfd_out = -1; for (int i = 0; i < REACTOR_CHANNELS; i++) { int pair[2]; if (pipe2(pair, O_NONBLOCK | O_CLOEXEC) == -1) { int saved = errno; for (int j = 0; j < i; j++) { (void)close(rd_fds[j]); (void)close(wr_fds[j]); } errno = saved; return -1; } rd_fds[i] = pair[0]; wr_fds[i] = pair[1]; } int evfd = eventfd(0U, EFD_NONBLOCK | EFD_CLOEXEC); if (evfd == -1) { int saved = errno; for (int i = 0; i < REACTOR_CHANNELS; i++) { (void)close(rd_fds[i]); (void)close(wr_fds[i]); } errno = saved; return -1; } *evfd_out = evfd; return 0; } static void consume_complete_frames( uint8_t accum[REACTOR_FRAME_BYTES], size_t *accum_len, const uint8_t *chunk, size_t n, struct reactor_stats *out ) { for (size_t i = 0U; i < n; i++) { accum[*accum_len] = chunk[i]; (*accum_len)++; if (*accum_len == REACTOR_FRAME_BYTES) { uint32_t word0 = 0U, word1 = 0U, word2 = 0U, word3 = 0U; memcpy(&word0, accum + 0U, 4U); memcpy(&word1, accum + 4U, 4U); memcpy(&word2, accum + 8U, 4U); memcpy(&word3, accum + 12U, 4U); out->xor_sum ^= (word0 ^ word1 ^ word2 ^ word3); out->total_frames++; *accum_len = 0U; } } } int reactor_run_loop(const int rd_fds[REACTOR_CHANNELS], int evfd, struct reactor_stats *out) { if (rd_fds == NULL || evfd < 0 || out == NULL) { errno = EINVAL; return -1; } memset(out, 0, sizeof(*out)); int epfd = epoll_create1(EPOLL_CLOEXEC); if (epfd == -1) { return -1; } for (uint32_t i = 0U; i < (uint32_t)REACTOR_CHANNELS; i++) { struct epoll_event ev = {.events = EPOLLIN | EPOLLET, .data.u32 = i}; if (epoll_ctl(epfd, EPOLL_CTL_ADD, rd_fds[i], &ev) == -1) { int saved = errno; (void)close(epfd); errno = saved; return -1; } } struct epoll_event stop_ev = {.events = EPOLLIN | EPOLLET, .data.u32 = 99U}; if (epoll_ctl(epfd, EPOLL_CTL_ADD, evfd, &stop_ev) == -1) { int saved = errno; (void)close(epfd); errno = saved; return -1; } uint8_t accum[REACTOR_CHANNELS][REACTOR_FRAME_BYTES]; size_t accum_len[REACTOR_CHANNELS] = {0}; memset(accum, 0, sizeof(accum)); uint32_t eof_mask = 0U; while (eof_mask != ((1U << REACTOR_CHANNELS) - 1U) || out->stop_counter == 0U) { struct epoll_event events[8]; int nready = epoll_wait(epfd, events, 8, 2000); if (nready == -1) { if (errno == EINTR) { continue; } int saved = errno; (void)close(epfd); errno = saved; return -1; } if (nready == 0) { (void)close(epfd); errno = ETIMEDOUT; return -1; } for (int i = 0; i < nready; i++) { uint32_t tag = events[i].data.u32; if (tag == 99U) { for (;;) { uint64_t val = 0U; ssize_t r = read(evfd, &val, sizeof(val)); if (r == (ssize_t)sizeof(val)) { out->stop_counter += val; } else if (r == -1 && errno == EAGAIN) { break; } else { break; } } } else if (tag < (uint32_t)REACTOR_CHANNELS) { uint8_t chunk[19]; for (;;) { ssize_t r = read(rd_fds[tag], chunk, sizeof(chunk)); if (r > 0) { out->total_bytes += (size_t)r; consume_complete_frames(accum[tag], &accum_len[tag], chunk, (size_t)r, out); } else if (r == 0) { if ((eof_mask & (1U << tag)) == 0U) { eof_mask |= (1U << tag); out->channels_eof++; (void)epoll_ctl(epfd, EPOLL_CTL_DEL, rd_fds[tag], NULL); } break; } else if (errno == EAGAIN || errno == EWOULDBLOCK) { out->eagain_drains++; break; } else if (errno == EINTR) { continue; } else { int saved = errno; (void)close(epfd); errno = saved; return -1; } } } } } (void)epoll_ctl(epfd, EPOLL_CTL_DEL, evfd, NULL); (void)close(epfd); return 0; }solution: files/reactor.h
learner@ksa:~/gl-c03/lab-m01$ bat files/reactor.h File: files/reactor.h #ifndef KSA_REACTOR_H #define KSA_REACTOR_H #include <stddef.h> #include <stdint.h> #define REACTOR_CHANNELS 4 #define REACTOR_FRAME_BYTES 16U struct reactor_stats { uint32_t channels_eof; uint32_t total_frames; size_t total_bytes; uint32_t xor_sum; uint64_t stop_counter; uint32_t eagain_drains; }; int reactor_open_channels(int rd_fds[REACTOR_CHANNELS], int wr_fds[REACTOR_CHANNELS], int *evfd_out); int reactor_run_loop(const int rd_fds[REACTOR_CHANNELS], int evfd, struct reactor_stats *out); #endifRun the check
From labs/lab_m01_epoll_reactor/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-c03/lab-m01./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsok 2 - archives reactor.o into libreactor.a and links epoll_reactorok 3 - drains 25-frame bursts across 4 EPOLLET pipes until EAGAINok 4 - drains 40-frame bursts with deterministic XOR digest 0xf728e538ok 5 - observes 8-byte eventfd shutdown counter and deregisters EOF channels# pass 5/5On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:
learner@ksa:~/gl-c03/lab-m01./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsnot ok 2 - archives reactor.o into libreactor.a and links epoll_reactor --- message: 'libreactor.a (with reactor.o) or executable epoll_reactor missing' hint: 'archive reactor.o via ar rcs libreactor.a reactor.o and link epoll_reactor in files/Makefile' ...not ok 3 - drains 25-frame bursts across 4 EPOLLET pipes until EAGAIN --- message: 'expected "channels=4 frames=100 bytes=1600 xor_sum=0x2a11eb87 stop_evfd=1", got "channels=0 frames=0 bytes=0"' hint: 'open pipes with O_NONBLOCK and loop read() until errno == EAGAIN on every EPOLLET wakeup' ...not ok 4 - drains 40-frame bursts with deterministic XOR digest 0xf728e538 --- message: 'expected "channels=4 frames=160 bytes=2560 xor_sum=0xf728e538 stop_evfd=1", got "channels=0 frames=0 bytes=0"' hint: 'spawn the 4-channel burst producer in epoll_reactor.c and fold every 16-byte frame into xor_sum' ...not ok 5 - observes 8-byte eventfd shutdown counter and deregisters EOF channels --- message: 'stop_evfd=1 not reported in output "channels=0 frames=0 bytes=0"' hint: 'register eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC) on epfd and read its uint64_t counter on shutdown' ...# pass 1/5note: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....
inspect harness: check.sh
learner@ksa:~/gl-c03/lab-m01$ bat check.sh File: check.sh #!/bin/sh set -u PASS=0 TOTAL=5 clean_msg() { printf '%s' "$1" | tr '\r\n' ' ' | tr "'" '"' | sed 's/ */ /g; s/^ //; s/ $//' } emit_diag() { printf " ---\n message: '%s'\n hint: '%s'\n ...\n" "$(clean_msg "$1")" "$(clean_msg "$2")" } WORKDIR="$(mktemp -d "${TMPDIR:-/tmp}/ksa_lab_c03_m01.XXXXXX")" trap 'rm -rf "$WORKDIR"' EXIT printf 'TAP version 13\n1..%d\n' "$TOTAL" MISSING="" for req in files/Makefile files/reactor.h files/reactor.c files/epoll_reactor.c; do if [ ! -f "$req" ]; then MISSING="$MISSING $req" fi done BUILD_OK=0 if [ -n "$MISSING" ]; then echo "not ok 1 - builds with -std=c11 -Wall -Wextra and no warnings" emit_diag "missing required files:$MISSING" "keep Makefile, reactor.h, reactor.c, and epoll_reactor.c in files/" else cp -R files "$WORKDIR/build" if gcc -std=c11 -Wall -Wextra -Werror -pthread \ "$WORKDIR/build/reactor.c" "$WORKDIR/build/epoll_reactor.c" \ -o "$WORKDIR/strict_probe" >"$WORKDIR/gcc.out" 2>"$WORKDIR/gcc.err" && \ make -C "$WORKDIR/build" clean >"$WORKDIR/clean.out" 2>&1 && \ make -C "$WORKDIR/build" >"$WORKDIR/make.out" 2>"$WORKDIR/make.err"; then echo "ok 1 - builds with -std=c11 -Wall -Wextra and no warnings" PASS=$((PASS + 1)) BUILD_OK=1 else ERR="$(cat "$WORKDIR/gcc.err" "$WORKDIR/make.err" 2>/dev/null)" echo "not ok 1 - builds with -std=c11 -Wall -Wextra and no warnings" emit_diag "compiler/make failed: ${ERR:-non-zero exit}" "compile with -std=c11 -Wall -Wextra -Werror -pthread in files/Makefile" fi fi BIN_OK=0 if [ "$BUILD_OK" -eq 1 ] && [ -f "$WORKDIR/build/libreactor.a" ] && \ ar t "$WORKDIR/build/libreactor.a" 2>/dev/null | grep -q "reactor.o" && \ [ -x "$WORKDIR/build/epoll_reactor" ]; then echo "ok 2 - archives reactor.o into libreactor.a and links epoll_reactor" PASS=$((PASS + 1)) BIN_OK=1 else echo "not ok 2 - archives reactor.o into libreactor.a and links epoll_reactor" emit_diag "libreactor.a (with reactor.o) or executable epoll_reactor missing" "archive reactor.o via ar rcs libreactor.a reactor.o and link epoll_reactor in files/Makefile" fi OUT25="" OUT40="" if [ "$BIN_OK" -eq 1 ]; then OUT25="$(timeout 3 "$WORKDIR/build/epoll_reactor" 25 2>&1 || true)" OUT40="$(timeout 3 "$WORKDIR/build/epoll_reactor" 40 2>&1 || true)" elif [ -x "$WORKDIR/build/epoll_reactor" ]; then OUT25="$(timeout 3 "$WORKDIR/build/epoll_reactor" 25 2>&1 || true)" OUT40="$(timeout 3 "$WORKDIR/build/epoll_reactor" 40 2>&1 || true)" fi EXP25="channels=4 frames=100 bytes=1600 xor_sum=0x2a11eb87 stop_evfd=1" case "$OUT25" in *"channels=4 frames=100 bytes=1600 xor_sum=0x2a11eb87"*) echo "ok 3 - drains 25-frame bursts across 4 EPOLLET pipes until EAGAIN" PASS=$((PASS + 1)) ;; *) echo "not ok 3 - drains 25-frame bursts across 4 EPOLLET pipes until EAGAIN" emit_diag "expected '$EXP25', got '${OUT25:-empty}'" "open pipes with O_NONBLOCK and loop read() until errno == EAGAIN on every EPOLLET wakeup" ;; esac EXP40="channels=4 frames=160 bytes=2560 xor_sum=0xf728e538 stop_evfd=1" if [ "$OUT40" = "$EXP40" ]; then echo "ok 4 - drains 40-frame bursts with deterministic XOR digest 0xf728e538" PASS=$((PASS + 1)) else echo "not ok 4 - drains 40-frame bursts with deterministic XOR digest 0xf728e538" emit_diag "expected '$EXP40', got '${OUT40:-empty}'" "spawn the 4-channel burst producer in epoll_reactor.c and fold every 16-byte frame into xor_sum" fi case "$OUT25" in *"stop_evfd=1") echo "ok 5 - observes 8-byte eventfd shutdown counter and deregisters EOF channels" PASS=$((PASS + 1)) ;; *) echo "not ok 5 - observes 8-byte eventfd shutdown counter and deregisters EOF channels" emit_diag "stop_evfd=1 not reported in output '${OUT25:-empty}'" "register eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC) on epfd and read its uint64_t counter on shutdown" ;; esac printf '# pass %d/%d\n' "$PASS" "$TOTAL" [ "$PASS" -eq "$TOTAL" ]Definition of done
Verification checklist
status: 0/3 checks verified
Troubleshooting
Compiler fails under -Werror on sign conversion or unused args
Use exact POSIX return types (ssize_t for read()/write(), size_t for byte counts) rather than relaxing flags.
./check.sh reports missing files in files/
Invoke ./check.sh from inside labs/lab_m01_epoll_reactor/ so relative paths to files/ resolve directly.