The Complete Guide to I/O Multiplexing: select, poll, epoll and kqueue
Learn I/O multiplexing in C: select, poll, epoll and kqueue compared, with event loops, edge and level triggering, partial I/O, timers and scaling across cores.

A network server spends almost all of its life waiting. It waits for a client to connect, for a request to arrive, for a send buffer to drain, for a timer to expire. The design question that decides what the server looks like is how it waits: one thing at a time, or for many things at once. I/O multiplexing is the answer to the second: you hand the kernel a set of descriptors and sleep in a single call until one of them is ready, then do exactly the work that is now possible. Every event loop in every language, from Node.js to nginx to Redis, rests on it. This guide covers the four classic interfaces, select, poll, epoll and kqueue, with the same echo server in each shape, what makes them differ in cost and behavior, how to build the loop around them correctly, and where the next generation (io_uring and completion ports) fits. It is the hub for the rest of this series, and each section points to a focused post that goes deeper. Examples target Linux 6.12 with glibc 2.40, and FreeBSD 14 and macOS 15 where kqueue is covered.
Why one thread waiting on one socket does not scale
Start with the simplest server, a loop that accepts a client and reads from it until it disconnects:
for (;;) {
int c = accept(listener, NULL, NULL);
char buf[512];
ssize_t n;
while ((n = read(c, buf, sizeof buf)) > 0)
write(c, buf, (size_t)n);
close(c);
}Every call that can wait does wait, and while the thread waits inside read for client A it cannot serve client B. B's connection completes at the kernel level, because the handshake needs no help from your program, and then sits in the listen queue until A is done. For a program with one user at a time that is fine. For anything else it is a serious flaw, and the first reaction is to run each client in its own thread or process. That works, and it is still a reasonable design for tens or hundreds of connections. The cost grows with the number of clients: each thread has a kernel stack and a user stack, the scheduler has to track them all, and switching between them costs cache and time. A server with ten thousand mostly idle clients does not have ten thousand things to do. It has a few things to do and ten thousand things to watch, and it needs a way to watch cheaply. That observation is the heart of the C10K discussion, which is retold in the C10K problem and how event loops solve it.
I/O multiplexing separates watching from doing. One thread asks the kernel "tell me which of these descriptors is ready", sleeps until the answer is non-empty, and then does the ready work without blocking, because ready means exactly that the operation can proceed now. The thread never sleeps inside a read on one client while another needs service. It sleeps in the multiplexing call, which wakes for whichever client speaks first.
Readiness is the model, and completion is the alternative
Before the interfaces, the distinction that organizes all of them. select, poll, epoll and kqueue are readiness interfaces. They tell you that a descriptor is now readable or writable, meaning a read or write will not block, and then you perform the call. The kernel's job is notification, and yours is the transfer. This is also called the reactor pattern: the loop reacts to events by invoking handlers.
The other model is completion: you start an operation by giving the kernel a buffer, the kernel does the transfer, and later it tells you the operation finished. Windows I/O completion ports work this way, and so does Linux io_uring. It is also called the proactor pattern. The practical consequence is who owns the buffer: in readiness, the buffer exists only during your read call, while in completion, the buffer must stay valid from submission until the notification, which can be long. The comparison across platforms is in epoll vs kqueue vs IOCP, and the Linux completion interface in what io_uring is. This guide is about readiness, because it is what you will meet first and in most production code.
Non-blocking sockets are part of the contract
A readiness notification is a hint, not a promise that holds forever. Between the kernel saying "readable" and your read, another thread may have read the data, or a packet may have been discarded after a checksum failure, so the call can still block. And for writes, "writable" means some space is free, not that your whole buffer fits. The safe contract is: every descriptor in the loop is non-blocking, so that when the hint is wrong the call returns EAGAIN instead of freezing the loop.
Setting it is three lines with fcntl, or one flag with SOCK_NONBLOCK and accept4 on Linux, as detailed in making a socket non-blocking. The conceptual background, including what EAGAIN means and why you never spin on it, is in blocking vs non-blocking I/O explained. One Linux detail catches people: a socket returned by accept does not inherit the listener's non-blocking flag, so the accepted socket must be set non-blocking explicitly or with accept4.
A correct non-blocking handler treats three outcomes of read: a positive count (data), zero (the peer closed) and -1 with EAGAIN (nothing now, wait for the next notification). write has the same shape, with the added case that a positive count may be less than you asked for.
select: the oldest interface
select takes three bitmaps of descriptors (to watch for reading, writing and exceptional conditions), the highest descriptor number plus one and an optional timeout. It sleeps until a descriptor is ready or the timeout expires, then returns the number ready and rewrites the bitmaps to hold only the ready ones.
fd_set ready;
for (;;) {
FD_ZERO(&ready);
FD_SET(listener, &ready);
int maxfd = listener;
for (int i = 0; i < nclients; i++) {
FD_SET(clients[i], &ready);
if (clients[i] > maxfd)
maxfd = clients[i];
}
if (select(maxfd + 1, &ready, NULL, NULL, NULL) < 0)
continue; /* EINTR */
if (FD_ISSET(listener, &ready))
accept_client();
for (int i = 0; i < nclients; i++)
if (FD_ISSET(clients[i], &ready))
serve(clients[i]);
}Three properties define it. The sets are overwritten, so you rebuild them on every pass. The fd_set type is a fixed bitmap of FD_SETSIZE bits, 1024 on glibc, so no descriptor numbered 1024 or more can be watched, however few you watch; the mechanics and the failure when you exceed it are in how fd_set bitmaps work. And each call costs time proportional to the highest descriptor number, since the kernel scans the bitmap and you scan it again. A full walkthrough with a working server is in handling multiple clients with select. Use select for small tools, for code that must also run on systems with nothing newer, and for teaching. Its sibling pselect adds a nanosecond timeout and an atomically applied signal mask.
poll: the same idea without the ceiling
poll replaces the bitmaps with an array of struct pollfd, each holding a descriptor, the events you want and a field the kernel fills with the events that occurred. There is no maximum descriptor number and nothing to rebuild, because the request and the answer live in different fields.
struct pollfd fds[MAX];
int n = 1;
fds[0] = (struct pollfd){ .fd = listener, .events = POLLIN };
for (;;) {
if (poll(fds, (nfds_t)n, -1) < 0)
continue;
if (fds[0].revents & POLLIN)
accept_into(fds, &n);
for (int i = 1; i < n; i++) {
if (fds[i].revents & (POLLIN | POLLHUP | POLLERR))
serve(&fds[i]);
}
}The error events POLLERR, POLLHUP and POLLNVAL are reported without being requested, so handlers must check for them, and a negative fd makes poll skip the entry, which is the clean way to free a slot. What poll does not fix is the cost model: every call passes the whole array into the kernel, which examines every entry, and then your loop scans the array again. Both are O(n) in the number of descriptors, so a server with fifty thousand idle connections burns CPU on bookkeeping with nothing to do. Conversion from select and the revents details are covered in using poll instead of select. poll is a good default for portable POSIX code with hundreds of descriptors, and ppoll adds the nanosecond timeout and signal-mask atomicity on Linux.
epoll: registration once, readiness lists forever
select and poll are stateless: the kernel rebuilds its picture of your descriptors on every call. epoll, added in Linux 2.5.44, keeps that picture in the kernel. You create an epoll instance, register each descriptor once, and epoll_wait returns only the ones that are ready. Cost follows the number of ready descriptors, not the number registered. The mechanism, a wait-queue callback on each file that appends to a ready list, is traced in how epoll works inside the kernel.
The API is three calls:
int ep = epoll_create1(EPOLL_CLOEXEC);
struct epoll_event ev = { .events = EPOLLIN, .data.fd = listener };
epoll_ctl(ep, EPOLL_CTL_ADD, listener, &ev);
struct epoll_event events[64];
for (;;) {
int n = epoll_wait(ep, events, 64, -1);
for (int i = 0; i < n; i++) {
int fd = events[i].data.fd;
if (fd == listener) {
int c = accept4(listener, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC);
struct epoll_event cev = { .events = EPOLLIN, .data.fd = c };
epoll_ctl(ep, EPOLL_CTL_ADD, c, &cev);
} else {
serve(fd, events[i].events);
}
}
}epoll_create1 makes the instance, epoll_ctl adds, modifies or removes a descriptor, and epoll_wait collects ready events into an array you provide. The data union returns to you unchanged, so it can carry the descriptor or a pointer to your per-connection struct, which saves a table lookup per event. A complete, commented echo server is in building an epoll event loop step by step, and the full list of flags, events and error codes is in the epoll cheat sheet. Two limits to know: regular files and directories cannot be registered (EPERM), because they are always "ready", and the number of watches per user is capped by /proc/sys/fs/epoll/max_user_watches.
Level-triggered and edge-triggered delivery
epoll has two delivery modes, and choosing between them is the decision that most often goes wrong. Level-triggered, the default, behaves like poll: as long as a descriptor is ready, every epoll_wait reports it. If you read only half of what is waiting, the next wait reports the rest. Edge-triggered, selected with EPOLLET, reports a descriptor only when its state changes, for example when new data arrives. If you read half and stop, the other half sits in the kernel and nothing will announce it until more data arrives.
Edge mode saves wakeups, since a busy descriptor is not reported repeatedly, and it removes some epoll_ctl calls. It also demands discipline: every notification must be followed by reading until EAGAIN, on a non-blocking descriptor, so that nothing is left behind. A program output that shows the same descriptor reported three times in level mode and once in edge mode, with the unread bytes stranded, is in level-triggered vs edge-triggered epoll, which also contains the decision table. The standard recommendation is to write the loop level-triggered, make it correct and measure it, and move to edge-triggered only if profiling shows wakeups matter. The frequent hazard that arises when you do, handling a message split across several reads, is the subject of partial reads with edge-triggered epoll.
kqueue: the BSD and macOS counterpart
FreeBSD, macOS, OpenBSD and NetBSD have kqueue, which came out of FreeBSD 4.1 and is more general than epoll. One call, kevent, both applies changes and waits for events. Each registration is a filter on an identifier: EVFILT_READ and EVFILT_WRITE for sockets, but also EVFILT_TIMER, EVFILT_SIGNAL, EVFILT_PROC and EVFILT_VNODE, so timers, signals, child exits and file changes arrive through the same queue as network events, with no extra descriptors.
int kq = kqueue();
struct kevent change;
EV_SET(&change, listener, EVFILT_READ, EV_ADD, 0, 0, NULL);
kevent(kq, &change, 1, NULL, 0, NULL);
struct kevent events[64];
for (;;) {
int n = kevent(kq, NULL, 0, events, 64, NULL);
for (int i = 0; i < n; i++) {
int fd = (int)events[i].ident;
if (fd == listener) {
int backlog = (int)events[i].data; /* connections waiting */
while (backlog-- > 0)
accept_and_register(kq, listener);
} else if (events[i].flags & EV_EOF) {
close(fd);
} else {
serve(fd);
}
}
}Two conveniences stand out. On a listener, data is the number of connections ready to accept, and on a connected socket it is the number of bytes available. And end of file arrives as the EV_EOF flag on the event, which may come together with remaining data. Level-triggered is the default, EV_CLEAR makes a filter edge-triggered, and EV_DISPATCH gives the one-shot behavior of EPOLLONESHOT. The full BSD walkthrough, including the macOS differences such as the missing accept4, is in writing an event loop with kqueue.
Completion ports and io_uring as the other family
Windows has I/O completion ports and Linux has io_uring; both follow the completion model described earlier. They matter for this guide in two ways. First, they are the reason that a portable event abstraction is harder than it looks: a loop written around "tell me when I can read" does not map onto "tell me when the read finished" without an adapter layer. Libraries such as libuv present a completion-style API and implement it over epoll, kqueue and IOCP, which is explained in using libuv or libevent instead of raw epoll. Second, they are the next step when system call overhead becomes the limit: io_uring batches many operations per system call and handles files and sockets in one interface. The Linux server design is in the complete guide to io_uring for network servers, and the trade-off in epoll vs io_uring.
The four interfaces side by side
select | poll | epoll | kqueue | |
|---|---|---|---|---|
| Platforms | everywhere | POSIX systems | Linux | BSD, macOS |
| Descriptor limit | numbers below FD_SETSIZE (1024) | none | none | none |
| What you pass each call | three bitmaps, rebuilt | the whole array | nothing, state is in the kernel | only changes |
| Cost per wait | O(highest fd) | O(n) | O(ready) | O(ready) |
| Trigger modes | level | level | level and edge | level, EV_CLEAR edge, one-shot |
| Beyond sockets | no | no | no timers or signals (use timerfd, signalfd) | timers, signals, processes, files |
| Registration | none | none | epoll_ctl per change | batched into kevent |
| Timeout resolution | microseconds | milliseconds | milliseconds (epoll_pwait2 nanoseconds on 5.11) | nanoseconds |
| Closing a watched fd | nothing to clean up | nothing to clean up | removed when the last duplicate closes | removed on close |
Choosing an interface
The decision is mostly about platform and scale, and the table gives a rule you can apply in a minute.
| Situation | Choose |
|---|---|
| A small tool or a lesson, any platform | select or poll |
| Portable POSIX server, hundreds of connections | poll |
| Linux server, thousands of connections or more | epoll |
| BSD or macOS server | kqueue |
| One codebase on Linux, BSD, macOS and Windows | libuv, libevent or similar |
| Linux, syscall cost is the measured bottleneck, or files in the same loop | io_uring |
If you are unsure, poll is the lowest-risk start, and the structure of a poll loop carries over to the other two with mechanical changes: the array of descriptors becomes a registration call, and the scan of revents becomes a loop over returned events.
The anatomy of a correct event loop
All of the interfaces support the same loop, and the interface matters less than the structure around it. Every correct readiness loop has these parts.
A table of connections. Each accepted socket has a struct with its descriptor, a read buffer, a write buffer, a parser state and a timestamp. The loop finds it from the event, either by a table indexed by descriptor, by a pointer in the event payload or by a map. The state is what lets a handler resume where it left off, because a handler runs to completion and returns, and the next event may be several milliseconds and a thousand other events later.
Handlers that never block. A handler reads what is available, makes progress, writes what it can, and returns. It never waits for more data, because waiting freezes every other connection. Anything that can take long, a disk read, a database call, a hash computation, is moved to a thread pool and its result returned to the loop through a queue and a wakeup descriptor such as an eventfd.
Output buffering. A write of a large reply may accept only part of it, or none, when the peer is slow. The handler stores the unsent tail in the connection's write buffer and asks to be told when the socket is writable again. Doing that correctly, and the CPU-spin trap in getting it wrong, is the topic of registering EPOLLOUT only while output is pending. The summary is that write interest is requested only while bytes are pending, because an idle socket is always writable and a permanent write registration makes a level-triggered loop spin at full CPU.
Careful connection teardown. A handler can close a connection while later events for it are still in the batch the kernel returned. Freeing the connection struct at that moment, or reusing the descriptor number for a new client in the same batch, produces use-after-free bugs and events delivered to the wrong peer. The robust pattern is to mark the connection dead, remove it from the interest set and free it after the whole batch is processed, which is worked through in deferred close for connection lifetimes.
Handling accept correctly
The listening socket has its own failure modes, and a server that ignores them works in tests and fails in production. A readable listener means accept will not block, but it may fail with several errors that are not fatal. EINTR means a signal arrived, so retry. ECONNABORTED and EPROTO mean the connection died in the queue before you accepted it, so continue to the next one. EAGAIN means the queue is empty.
The nasty one is EMFILE (the process has no descriptors left) or ENFILE (the system has none). The pending connection stays in the listen queue and the listener stays readable, so a level-triggered loop returns immediately, fails again and spins at full CPU while accepting nothing. Two remedies are common. Keep a spare descriptor open on /dev/null, and on EMFILE close it, accept and immediately close the new connection to drain the queue, then reopen the spare. Or stop watching the listener for a short interval and resume when connections close. Either keeps the server from spinning. A server that accepts in a loop until EAGAIN on each wakeup handles bursts with fewer system calls, and with edge-triggered mode it must do so.
Signals, SIGPIPE and EINTR
Three small details cause outsized trouble.
Writing to a socket whose peer has closed raises SIGPIPE, whose default action kills the process. A server must either ignore the signal with signal(SIGPIPE, SIG_IGN) or use send with MSG_NOSIGNAL, so that a write to a dead peer returns EPIPE instead. One client that disconnects at the wrong moment should not be able to terminate the server.
A signal that arrives while the loop sleeps interrupts the wait, which returns -1 with EINTR. That is not an error to handle by exiting; the loop should simply go round again. If a shutdown flag is set by a signal handler, the race between checking the flag and going to sleep needs ppoll, pselect or epoll_pwait, which swap in a signal mask atomically, or a self-pipe or signalfd so the signal becomes a readable descriptor in the loop itself.
Regular reads and writes can also fail with EINTR, so a robust handler retries them, though on non-blocking sockets it is rare.
Timers belong in the loop
A server needs time: a deadline for a client that connects and says nothing, a retransmission in a protocol, a periodic statistics line. Because the loop sleeps in the multiplexing call, the way to run timers is to make the sleep time-bounded. Keep the next deadline, compute the milliseconds until it, pass that as the timeout, and run the expired timers when the call returns. With epoll_wait and poll the timeout is in milliseconds, with kevent it is a timespec, and select takes a timeval.
For many connections, the data structure for timers matters. A sorted list is O(n) to insert. A min-heap makes insert and pop-minimum logarithmic, and a hashed timer wheel makes both constant for timeouts of similar length, which is the right choice for idle timeouts on a very large number of connections. A common simplification is a coarse sweep once a second over all connections, comparing a last_active timestamp to a limit, which costs a scan per second and nothing per message. On Linux you can also put a timer into epoll as a descriptor with timerfd_create, and on BSD you add an EVFILT_TIMER.
Scaling past one core
One loop uses one core. When that core is the limit, there are three well-understood designs, and each is a trade between sharing and isolation.
One loop plus a worker pool. The loop owns all network I/O and hands slow work, such as database calls or CPU-heavy requests, to a thread pool, receiving results back through a queue and an eventfd. This is the simplest way to add parallelism and it fits services whose cost is the work, not the I/O.
Shared epoll instance with several threads. All threads call epoll_wait on one instance. Events can reach any thread, so two threads can process the same connection at once unless the descriptor is registered with EPOLLONESHOT, which disables it after one event until you re-arm it. The pattern, with its re-arm discipline, is in using EPOLLONESHOT in multithreaded servers.
One loop per thread. Each thread has its own epoll instance, its own listening socket created with SO_REUSEPORT and its own connections, and connections never move between threads. There is no sharing on the hot path and no locking. This is the design behind most high-performance servers and is built in full in a multi-reactor server with one epoll per thread. If several instances must share one listening socket instead, EPOLLEXCLUSIVE stops all of them waking for each new connection, as explained in avoiding thundering herds. For the lowest latency on dedicated cores, epoll busy polling removes interrupt delay at the price of a spinning core.
Library or raw interface
Writing the loop yourself teaches the most and gives the most control. It also means owning every edge case in this guide, forever, on every platform you support. The libraries exist because those edge cases are the same for everyone. libuv, the library under Node.js, offers handles and completion-style callbacks with backends for epoll, kqueue and IOCP, and a thread pool for blocking work. libevent offers an event base with buffered events and ready-made helpers for HTTP and DNS. In Rust, mio is the thin readiness layer under Tokio, described in using non-blocking sockets in Rust with mio. The comparison with a working echo server in each of the first two is in libuv or libevent instead of raw epoll. The rule is simple: write the raw loop to learn it, or when you have a fixed platform and need a control the library hides, and use a library for anything that must be portable or maintained by a team.
Limits to raise before you load test
A server tested against its first thousand connections tends to fail on a system limit rather than on its own code. Check these before blaming the loop.
| Limit | Where to look | Symptom when hit |
|---|---|---|
| open files per process | ulimit -n, RLIMIT_NOFILE | accept fails with EMFILE |
| open files system-wide | /proc/sys/fs/file-max | ENFILE |
| listen backlog | the listen argument, capped by net.core.somaxconn | clients time out during connection bursts |
| ephemeral ports (on the client side) | net.ipv4.ip_local_port_range | clients run out of source ports to one destination |
| connection tracking | nf_conntrack_max | packets dropped, with a kernel log message |
| epoll watches | /proc/sys/fs/epoll/max_user_watches | epoll_ctl fails with ENOSPC |
| socket buffers | net.ipv4.tcp_rmem, tcp_wmem, tcp_mem | stalls and slow transfers at scale |
Raising ulimit -n has no effect on FD_SETSIZE, so a select-based server must be converted before it can use the extra descriptors, which is another reason to start with poll or epoll for anything that may grow.
Debugging an event loop
An event loop that misbehaves usually shows one of a handful of symptoms, and each has a cheap check.
A server that pins a core with no traffic is spinning, and the usual cause is a permanent write registration or an unhandled EMFILE on the listener. strace -c -p <pid> for a few seconds shows a wait call returning immediately and a flood of identical calls, and /proc/<pid>/fdinfo/<epfd> lists each registered descriptor's event mask, so a stuck EPOLLOUT bit is visible.
A connection that works for small requests and hangs for large ones points at a partial read or a missed re-arm: ss -tn shows a non-zero Recv-Q for a socket with data nobody read, which is the signature of a stranded edge-triggered notification or a disabled one-shot descriptor.
Intermittent crashes or wrong-peer data with many connections point at connection lifetime: build with -fsanitize=address and run a stress client that connects and disconnects at random.
For a quick look at what the loop is doing, strace -f -e trace=epoll_wait,epoll_ctl,accept4,read,write -p <pid> prints each call as it happens, which is enough to see whether a connection gets the expected sequence of events. And nc and ss between them cover most manual testing.
Half-closed connections and shutdown
A TCP connection has two directions, and either side can finish its own direction without ending the other. A client that sends a request and then calls shutdown(fd, SHUT_WR) tells the server "I have nothing more to send" while still waiting for the reply. On the server, that arrives as a readable event where read returns 0, the same signal as a full close. The difference is that the server can still write, so a loop that closes the descriptor the moment it sees end of file throws away the reply to every client that uses this style, which includes some command-line tools and several protocols that mark the end of a request by closing the sending side.
The safe handling is to treat a zero-byte read as "no more input", finish any processing, send the reply, and then close. On Linux, EPOLLRDHUP reports the peer's shutdown of its writing side without a read, which helps when you want to learn about it while data is still queued. EPOLLHUP is different: it means the connection is finished in both directions or was reset, and writing is pointless. A server that cares about the distinction keeps a flag per connection, peer_done_sending, and closes only when both the flag is set and the output buffer is empty. The server's own shutdown(fd, SHUT_WR) after the last byte of a reply is the polite way to say the response is complete, and it lets the client's read return 0 instead of waiting for a timeout.
What happens to a registration when a descriptor closes
The four interfaces disagree about what closing a descriptor does to your interest in it, and the disagreement causes real bugs. With select and poll there is no registration to clean: you simply stop putting the number in the set. The hazard is the opposite one, leaving a closed descriptor in your array, which poll reports with POLLNVAL and select rejects with EBADF.
With kqueue, closing the descriptor removes its filters, so the queue forgets it automatically. With epoll, the registration belongs to the open file description, not the descriptor number. Closing the last descriptor that refers to the file removes it. But if the description is shared, because of dup, dup2 or fork, a close on one descriptor leaves the registration alive, and epoll_wait keeps reporting events for a file you believe you closed, tagged with the old number. The remedy is to call epoll_ctl(EPOLL_CTL_DEL) before close whenever duplicates are possible. The kernel-side reason is that the registration is keyed by the pair of the file object and the descriptor number, as explained in how epoll works inside the kernel.
Datagram sockets in the same loop
Everything so far assumed stream sockets. UDP fits the same loop with two differences. Readiness means a whole datagram is waiting, and each recvfrom or recvmsg returns exactly one datagram regardless of the buffer size, truncating anything that does not fit. A level-triggered loop can read one datagram per wakeup, and an edge-triggered one must read until EAGAIN, since each arrival is a separate edge that may have been coalesced into one report.
The second difference is error reporting. ICMP errors, such as "port unreachable" after a send to a closed port, are queued on the socket and show up as EPOLLERR. The handler reads them with recvmsg and the MSG_ERRQUEUE flag, which is also how timestamps and extended error information are retrieved, as in packet timestamps with SO_TIMESTAMPING. A UDP server that ignores EPOLLERR leaves the error queued, and with level-triggered mode the event fires on every wait. For high datagram rates, recvmmsg reads many datagrams in one system call, which matters more for UDP than anything in the multiplexing layer itself.
Events that are not sockets
A real server needs more than network events, and the multiplexing call can wait on those too, if they are made into descriptors. On Linux the toolbox is small and consistent.
An eventfd is a counter with a descriptor. Writing to it from another thread makes it readable, which is the standard way to wake a loop that is asleep in epoll_wait, for example to deliver a finished job from a thread pool. A timerfd turns a one-shot or periodic timer into a descriptor that becomes readable on expiry, which puts idle timeouts and statistics ticks into the same loop with no signal handling. A signalfd converts blocked signals into readable data, so SIGTERM and SIGHUP arrive as ordinary events, which solves the race between a signal handler and going to sleep. A pipe or a Unix domain socket pair does the same job as eventfd when you need to carry data and not just a count. On BSD and macOS none of these are needed, because kqueue has native filters for timers, signals and process exit. Whatever the platform, the principle is the same: anything the loop must react to should be something the loop can wait on, so that the program has one place where it sleeps.
A line-based protocol as a state machine
Most handlers end up as small state machines, and it helps to see one in the plainest case. Consider a protocol where each request is one line ending in a newline, and the server replies with one line. A connection needs a read buffer, a count of bytes held and an output buffer. When the descriptor is readable, the handler reads what is available and appends it to the read buffer. It then loops: look for a newline in the buffer, and if there is one, extract the line, produce the reply into the output buffer, and shift the remaining bytes to the front. If there is no newline, it stops and waits for more data, keeping the partial line. Finally it tries to write the output buffer, and if the socket accepts only part of it, it registers for write readiness and returns.
Three properties make this robust. The handler never assumes a read contains a whole request or only one. It never blocks waiting for the rest of a line, because the rest arrives as a later event. And it bounds the buffer, closing the connection if a line grows past the limit, because otherwise a client that never sends a newline can make the server allocate without end. Every protocol parser in an event loop is this shape, with a different rule for when a message is complete. The treatment for length-prefixed framing, including the edge-triggered complication, is in handling partial reads.
Where to go next
This guide is the map. The posts it links to are the territory, and they are arranged to climb. If you are new to the vocabulary, start with blocking vs non-blocking I/O and making a socket non-blocking, then write a loop with select and poll. Next, build the epoll loop and learn the two trigger modes. For BSD and macOS, read the kqueue post. Past that lie the production concerns: output buffering, connection lifetimes, multithreading, the kernel internals and busy polling, and, for the completion model, the io_uring guide.

