Build an epoll Event Loop in C Step by Step
Write a single-threaded TCP echo server on Linux with epoll_create1, epoll_ctl and epoll_wait, using non-blocking sockets and a clean accept and read loop.

select and poll make the kernel look at every descriptor you care about on every call. epoll moves that bookkeeping into the kernel: you register interest in a descriptor once, and each wait returns only the ones that are ready. That change is why a Linux server can watch tens of thousands of mostly idle connections from one thread. This post builds a working epoll echo server in C one step at a time, on Linux 6.12 with glibc 2.40. It assumes you know what non-blocking sockets are; the broader picture is in the guide to I/O multiplexing.
The three system calls
The epoll API in epoll(7) has three calls:
epoll_create1(flags)creates an epoll instance and returns a descriptor for it. PassEPOLL_CLOEXECso the descriptor does not leak acrossexec.epoll_ctl(epfd, op, fd, &event)adds (EPOLL_CTL_ADD), changes (EPOLL_CTL_MOD) or removes (EPOLL_CTL_DEL) a descriptor from the instance's interest list.epoll_wait(epfd, events, maxevents, timeout)sleeps until at least one registered descriptor is ready, then fillseventswith the ready ones and returns how many.
The structure that carries both the interest and the answer is struct epoll_event:
struct epoll_event {
uint32_t events; /* EPOLLIN, EPOLLOUT, EPOLLERR, EPOLLHUP, ... */
epoll_data_t data; /* your payload: fd, pointer, u32 or u64 */
};The data union is yours. The simplest use stores the descriptor in data.fd and looks it up on wakeup. Larger servers store a pointer to a per-connection struct in data.ptr instead, so the handler starts with all the state it needs.
Step 1: a non-blocking listening socket
The listener is non-blocking so accept returns EAGAIN instead of sleeping when no client is waiting. SOCK_NONBLOCK sets that at creation.
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/socket.h>
int make_listener(unsigned short port)
{
int fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (fd < 0)
return -1;
int one = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
struct sockaddr_in a = {
.sin_family = AF_INET,
.sin_port = htons(port),
.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
};
if (bind(fd, (struct sockaddr *)&a, sizeof a) < 0 || listen(fd, 128) < 0)
return -1;
return fd;
}Step 2: create the epoll instance and register the listener
int ep = epoll_create1(EPOLL_CLOEXEC);
if (ep < 0) { perror("epoll_create1"); return 1; }
struct epoll_event ev = { .events = EPOLLIN, .data.fd = listener };
if (epoll_ctl(ep, EPOLL_CTL_ADD, listener, &ev) < 0) {
perror("epoll_ctl listener");
return 1;
}EPOLLIN on a listening socket means a connection is ready to accept. The default mode is level-triggered, which behaves like poll: as long as the condition holds, every epoll_wait reports it. The alternative, edge-triggered mode, reports only changes and needs more care.
Step 3: the wait loop
struct epoll_event events[64];
for (;;) {
int n = epoll_wait(ep, events, 64, -1);
if (n < 0) {
if (errno == EINTR)
continue;
perror("epoll_wait");
return 1;
}
for (int i = 0; i < n; i++) {
int fd = events[i].data.fd;
if (fd == listener)
on_accept(ep, listener);
else
on_client(ep, fd, events[i].events);
}
}The array of 64 caps how many events one wakeup handles; extra ready descriptors stay ready and appear in the next call. A timeout of -1 waits forever; use a millisecond value if you need periodic housekeeping.
Step 4: accepting every pending client
With level-triggered mode, accepting once per wakeup is correct, because the listener stays ready while connections remain queued. Draining in a loop is still a good habit and saves wakeups under bursts:
static void on_accept(int ep, int listener)
{
for (;;) {
int c = accept4(listener, NULL, NULL, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (c < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK)
return; /* queue drained */
if (errno == EINTR)
continue;
perror("accept4");
return;
}
struct epoll_event ev = { .events = EPOLLIN, .data.fd = c };
if (epoll_ctl(ep, EPOLL_CTL_ADD, c, &ev) < 0) {
perror("epoll_ctl client");
close(c);
continue;
}
printf("accepted fd %d\n", c);
}
}accept4 returns the client already non-blocking, so no fcntl is needed. On Linux an accepted socket does not inherit the listener's non-blocking flag, which is why the flag is passed explicitly here.
Step 5: reading and echoing
static void on_client(int ep, int fd, uint32_t revents)
{
if (revents & (EPOLLERR | EPOLLHUP)) {
close(fd); /* close removes it from every epoll set */
return;
}
char buf[1024];
ssize_t n = read(fd, buf, sizeof buf);
if (n > 0) {
ssize_t off = 0;
while (off < n) {
ssize_t w = write(fd, buf + off, (size_t)(n - off));
if (w < 0) {
if (errno == EAGAIN)
break; /* real servers queue the rest; see below */
close(fd);
return;
}
off += w;
}
} else if (n == 0) {
printf("closed fd %d\n", fd);
close(fd);
} else if (errno != EAGAIN && errno != EINTR) {
close(fd);
}
(void)ep;
}Two things here are shortcuts. First, when write returns EAGAIN the program drops the rest of the buffer, which is acceptable for a demo that echoes small lines and wrong for a real server. The fix is to buffer the unsent bytes per connection and ask for EPOLLOUT only while they exist, as shown in registering EPOLLOUT only when output is pending. Second, closing a descriptor removes it from the epoll interest list automatically, provided no duplicate of that open file description is still open elsewhere, for example after a dup or a fork. The epoll(7) page spells out that caveat. Calling epoll_ctl(EPOLL_CTL_DEL) before close removes any doubt.
The whole program
Put the pieces together in one file:
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdint.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <unistd.h>
static void on_accept(int ep, int listener);
static void on_client(int ep, int fd, uint32_t revents);
int make_listener(unsigned short port);
int main(void)
{
int listener = make_listener(7003);
if (listener < 0) { perror("listener"); return 1; }
int ep = epoll_create1(EPOLL_CLOEXEC);
if (ep < 0) { perror("epoll_create1"); return 1; }
struct epoll_event ev = { .events = EPOLLIN, .data.fd = listener };
epoll_ctl(ep, EPOLL_CTL_ADD, listener, &ev);
puts("listening on 127.0.0.1:7003");
struct epoll_event events[64];
for (;;) {
int n = epoll_wait(ep, events, 64, -1);
if (n < 0) {
if (errno == EINTR)
continue;
perror("epoll_wait");
return 1;
}
for (int i = 0; i < n; i++) {
int fd = events[i].data.fd;
if (fd == listener)
on_accept(ep, listener);
else
on_client(ep, fd, events[i].events);
}
}
}Combine it with make_listener, on_accept and on_client from the steps above (or paste them into the same file) and compile with gcc -O2 -Wall epoll_echo.c -o epoll_echo. Two clients connecting and leaving produce output like this; descriptor numbers will vary:
listening on 127.0.0.1:7003
accepted fd 5
accepted fd 6
closed fd 6
closed fd 5The listener is 3 and the epoll instance is 4, so the first client is 5 in a typical run. Descriptors 0 to 2 are standard input, output and error.
What this loop teaches
The structure is the same for every epoll server: one wait call, a dispatch on the descriptor, and short non-blocking handlers that never sleep. Anything that can block, a disk read or a slow database call, stalls every connection, because there is one thread. That is the cost of the model, and the reason larger servers run one loop per core and send slow work to a thread pool.
When not to write this yourself
Hand-rolled epoll loops are fine for a learning project or a narrowly scoped daemon. A product that needs timers, cross-platform support and safe cleanup is usually better served by libuv or libevent, which handle the corner cases once.
Handling the epoll events correctly
epoll_wait fills the events field with a bitmask that can carry more than one flag at a time, so the handler tests bits and never compares for equality. A client socket that sends data and then closes can arrive as EPOLLIN | EPOLLHUP in a single event, and the right response is to read first, because buffered data is still waiting, and close only when read returns 0. The demo handler above closes immediately on EPOLLHUP, which is acceptable for an echo server and wrong for a protocol where the last request can arrive in the same segment as the FIN. A careful loop reads until EAGAIN or end of file whenever EPOLLIN is set and treats EPOLLERR and EPOLLHUP as reasons to read once more and then close.
Per-connection state with a pointer in data
The demo stores a descriptor number in data.fd and finds everything else by looking it up. Real servers allocate a small struct for each connection holding its descriptor, a read buffer, a write buffer, a parse state and a timestamp for idle timeouts, and register the pointer in data.ptr. The wake-up then needs no table lookup: cast the pointer and call the handler. The cost is lifetime management. Freeing the struct while an event for it is still in the array returned by epoll_wait produces a use-after-free, because the kernel does not know you freed it. The usual fix is to defer the free until the end of the loop iteration, covered in deferred close for connection lifetimes.
Testing the loop without writing a client
You can exercise the server from a shell. In one terminal start the program; in two others run nc 127.0.0.1 7003, type a line in each and press Enter. Each line returns immediately, even while the other client sits idle, which is the observable proof that one thread is serving both. Closing a client with Ctrl-D prints the closed fd line. To watch the system calls as they happen, run the server under strace -f -e trace=epoll_wait,epoll_ctl,accept4 ./epoll_echo and note that an idle server shows one blocked epoll_wait and nothing else, in contrast to a polling loop that would print a stream of calls.

