Module 2 · Lesson 75 of 131

Level-triggered vs edge-triggered epoll

Distinguish level-triggered from edge-triggered epoll, drain a nonblocking socket to EAGAIN, and explain why epoll outscales select and poll at high descriptor counts.

  • Beginner to advanced
  • 9 min read
  • 70 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, gcc, and a terminal with make for the benchmark lab.

Your place in the module
By the end you can 4 objectives
  • Distinguish level-triggered from edge-triggered epoll semantics.
  • Write a correct read-until-EAGAIN drain loop on a nonblocking socket.
  • Explain the per-call cost of select and poll versus epoll and when each is appropriate.
  • Choose EPOLLET, EPOLLONESHOT and EPOLLRDHUP for a real server loop.
Video coming soonLevel-triggered vs edge-triggered epoll
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from The epoll API and its event flags
  • epoll keeps the interest list in the kernel and returns only ready descriptors, so its cost scales with readiness, not with the number watched.
  • struct epoll_event carries an events bit mask and a data union that epoll_wait returns unchanged.
  • EPOLLERR and EPOLLHUP are reported even when not requested, so handlers must check for them.
01

Two trigger modes: readiness vs change

3 min read

You now have the epoll calls. This lesson explains its two trigger modes, why edge triggering demands nonblocking sockets, and why epoll outscales select and poll.

epoll_wait returns every descriptor that is currently ready. The default behaviour is If you return from epoll_wait having read only part of the data, the next call reports the same descriptor again, because the condition still holds. Nothing is lost if you under-read.

Adding EPOLLET to the events field switches the descriptor to The notification describes the transition, not the current amount of data. Suppose two kilobytes arrive and you read one kilobyte before returning to epoll_wait. In LT mode the descriptor is reported again, because one kilobyte remains. In ET mode it is not: no new edge happened, and the remaining kilobyte stays unreported until at least one more byte arrives.

The two modes answer different questions. LT answers "is this descriptor ready right now?" and keeps answering until the condition clears. ET answers "did something new happen?" and hands you the work once. LT reports readiness that persists; ET reports the completion event you are expected to finish. You set EPOLLET at EPOLL_CTL_ADD time, or later with EPOLL_CTL_MOD, to select ET for one descriptor. The semantics are defined in epoll(7).

Behaviour Level-triggered Edge-triggered
Reported while the condition holds only when the state changes
After a partial read reported again next wait not reported until new data
Blocking descriptor allowed must be nonblocking
Missed-data risk none, it is re-reported high unless you drain to EAGAIN

ET is the usual choice of high-throughput servers because a descriptor that keeps receiving data wakes the loop once per batch of arrivals instead of once per loop iteration. The price is the discipline the next section describes.

Level-triggered vs edge-triggeredLevel-triggeredEdge-triggeredReports whenconditionstill holdsstate changesAfter a partialreadre-reportednext waitnot reporteduntil newdataBlockingdescriptorallowedmust benonblockingMissed datanone, itre-reportsmust readuntil EAGAIN
Level-triggered mode re-reports a still-ready descriptor; edge-triggered mode reports only the transition.
02

Why edge triggering demands nonblocking sockets

5 min read

Because ET reports the transition once, the loop must read until the receive buffer is empty, or the leftover bytes are never reported again. The only reliable way to know the buffer is empty is to call read() until it returns -1 with errno set to EAGAIN. On a blocking socket that final read() does not return EAGAIN: it blocks until more data arrives, so the loop can never return to epoll_wait and every other descriptor is starved. This is why ET only works with nonblocking descriptors.

Make descriptors nonblocking with fcntl on an accepted socket, or avoid the extra call by passing SOCK_NONBLOCK to accept4() (and to socket() when you create the socket). On Linux EAGAIN and EWOULDBLOCK are the same value; test either.

c
/* fd is nonblocking and registered with EPOLLIN | EPOLLET. */
for (;;) {
    char buf[4096];
    ssize_t n = read(fd, buf, sizeof(buf));
    if (n > 0) {
        handle_input(fd, buf, (size_t)n);
    } else if (n == 0) {
        close(fd);            /* peer closed cleanly */
        break;
    } else if (errno == EAGAIN || errno == EWOULDBLOCK) {
        break;                /* buffer drained */
    } else {
        close(fd);            /* real error, e.g. ECONNRESET */
        break;
    }
}

This fragment needs <unistd.h> for read() and close(), and <errno.h> for errno and EAGAIN. Each branch matters. n > 0 processes one chunk and loops again, because read() is allowed to return fewer bytes than requested even when more remain. n == 0 means the peer closed its write half and the buffer is now empty: that is end-of-file, not a transient condition, so close the descriptor. EAGAIN means the buffer is drained and there is nothing more right now: break and return to epoll_wait. Any other errno is a real error.

The loop, not the single read, is what makes ET correct. A partial read returns 2 bytes when you asked for 4096 and the peer has sent only 2 so far; stopping there would leave the next chunk unreported. LT tolerates that stop because the descriptor is reported again while data remains. ET does not, so the loop runs to EAGAIN on every EPOLLIN event.

The same rule applies to writes: an ET descriptor with EPOLLOUT should be written until write() returns EAGAIN, because the kernel reports a writable buffer only when space first appears. Partial writes need the same loop with a moving pointer. This lesson stays on reads; the lab exercises both directions through an echo server.

Going deeperExplore the mechanism

The drain loop hides a starvation risk. If one client keeps data flowing faster than the loop reads it, read() never returns EAGAIN, the loop never exits, and every other client waits. Two tools keep this bounded. First, TCP flow control applies backpressure on its own: a receive buffer you stop draining fills up, the advertised window shrinks, and the sender's send() eventually blocks. Second, bound the work per descriptor: process up to N bytes, then stop even if the buffer is not empty. Because stopping before EAGAIN in ET discards the notification, pair this with EPOLLONESHOT, which disables the descriptor after one event, and re-arm it with epoll_ctl(epfd, EPOLL_CTL_MOD, ...) after processing. Re-arming re-checks current readiness, so data still waiting produces a fresh event and nothing is lost, while other descriptors get their turn.

Peer shutdown needs one more flag. EPOLLRDHUP is reported when the peer closes its write half: it called shutdown(fd, SHUT_WR) or close(). It is distinct from EPOLLHUP, a full hangup, and from read() returning 0, which is EOF after the buffer drains. EPOLLERR and EPOLLHUP are always reported without being requested; EPOLLRDHUP is not: it appears in the returned events only if you put it in the events mask when you register the descriptor. In ET, a peer that sends a final request and then half-closes may deliver EPOLLIN and EPOLLRDHUP together: drain the remaining data first, then read() returns 0, then close. Closing on EPOLLRDHUP before draining discards buffered data. The flag matters for request/response protocols, where a half-close still permits the server to write its reply before closing. See epoll_ctl(2).

Edge-triggered drain loopread()ProcessEOFpeer closedDrainedEAGAINErrorTransitionsn > 0read()ProcessloopProcessread()n == 0read()EOFpeer closedEAGAINread()DrainedEAGAINother errnoread()Errorread()ProcessEOFpeer closedDrainedEAGAINErrorTransitionsn > 0read()ProcessloopProcessread()n == 0read()EOFpeer closedEAGAINread()DrainedEAGAINother errnoread()Error
The drain loop reads repeatedly, ending only on EOF or EAGAIN.
03

Why epoll outscales select and poll

4 min read

select(2) monitors three fd_set bitmasks: readable, writable and exceptional. Every call copies the whole fd_set into the kernel and back out, the kernel scans every descriptor number from 0 up to the highest one you passed, and the returned fd_set is overwritten, so you rebuild it before the next call. An fd_set is a fixed-size bitmask capped by FD_SETSIZE at 1024 descriptors. After the call you scan all descriptors again in user space to find which bits are set. The per-call cost is O(n) in the number of descriptors, even when one is ready.

poll(2) removes the 1024 ceiling: it takes a pollfd array of any size, and it does not destroy your input. But it still copies the whole array into the kernel on each call and writes every entry's revents back out, the kernel scans every entry, and you scan every revents field to find ready descriptors. The per-call cost is still O(n).

epoll separates registration from waiting. You register each descriptor once with epoll_ctl, then epoll_wait returns only the descriptors that are ready. The kernel does not rescan the whole interest set on every wait: it walks a ready list and copies just the ready events out. The cost of one epoll_wait is O(k), where k is the number of ready descriptors, independent of the total number registered.

select poll epoll
Descriptor limit 1024 (FD_SETSIZE) none none
Registration every call every call once, with epoll_ctl
Kernel work per call scan all fds scan all fds walk ready list
Copy per call whole fd_set, in and out whole array in, every revents out ready events only
Result which fds are ready which fds are ready only ready fds

The difference shows at scale. A server with 10,000 connections and 10 active: select and poll rescan and recopy all 10,000 descriptors on every event loop iteration, while epoll_wait returns 10 events. The gap grows with the connection count, which is why epoll is the high-scale multiplexer on Linux. select and poll remain perfectly good for a few dozen descriptors; the O(n) rescans dominate only once the descriptor count is large.

Going deeperExplore the mechanism

epoll keeps two kernel structures. Its interest set, every registered descriptor, lives in a red-black tree keyed by the (file descriptor, open file description) pair, so epoll_ctl add and delete cost O(log n) and are paid once per descriptor, not per wait. When an event fires, the kernel appends the descriptor to a ready list, a doubly-linked list of ready entries. A descriptor already on the list is not appended a second time, so a busy descriptor holds at most one slot. epoll_wait simply moves entries from the ready list into the caller's events array.

The copy cost is what separates epoll from select and poll at scale. select and poll copy their whole structures on every call: for 10,000 descriptors a poll call copies a 10,000-entry pollfd array (about 80 KB) into the kernel and writes 10,000 revents fields back out, then user code scans it again. epoll copies only the ready events, a few hundred bytes when few descriptors are active.

The ready list also gives fairness. It is a queue: a descriptor already waiting is not moved to the front when more data arrives for it, so a continuously busy descriptor cannot push others out of the batch. Each ready entry is handed to the caller once per wait, in list order.

select vs poll vs epollselectpollepollDescriptor limit1024(FD_SETSIZE)nonenoneRegistrationevery callevery callonceKernel workscan all fdsscan all fdsready listonlyCopy per callwhole fd_setwhole arrayready eventsonly
select and poll rescan and recopy the whole set each call; epoll returns only the ready descriptors.

This machinery is what the next lesson, "Folding signals, timers and accepts into epoll", builds on: once descriptors are registered and drained correctly, the same epoll_wait loop can also watch signal descriptors, timer descriptors and the listening socket.

Key takeaways

  • Level-triggered epoll re-reports a descriptor while its condition holds; edge-triggered reports only the transition, so unread data is not re-reported until new data arrives.
  • Edge-triggered mode requires nonblocking descriptors because the drain loop must end on EAGAIN, which a blocking read() never returns.
  • select and poll rescan and recopy the whole descriptor set on every call (O(n)); epoll registers once and returns only the ready descriptors (O(k)).
  • EPOLLRDHUP reports a peer's write-side close, and EPOLLERR and EPOLLHUP are always reported without being requested.
Reflect
  1. Explain to a colleague, in two sentences: distinguish level-triggered from edge-triggered epoll semantics.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close