0Pricing
C Academy · Lesson

The Event Loop

React to readable sockets.

The Heart of the Server

The event loop is the engine that drives an epoll server. It repeatedly waits for ready descriptors and dispatches work to handlers.

Its shape is always the same: call epoll_wait(), iterate the returned events, act on each, then loop again. Everything else hangs off this skeleton.

for (;;) {
    int n = epoll_wait(epfd, events, MAX_EVENTS, -1);
    for (int i = 0; i < n; i++) handle(&events[i]);
}

Calling epoll_wait

epoll_wait() takes the epoll fd, an output array of epoll_event, its capacity, and a timeout in milliseconds.

It blocks until at least one descriptor is ready (or the timeout elapses) and returns how many events were filled into your array. Only those entries are valid.

struct epoll_event events[MAX_EVENTS];
int n = epoll_wait(epfd, events, MAX_EVENTS, -1);
if (n == -1) { perror("epoll_wait"); }

All lessons in this course

  1. Blocking vs Non-Blocking I/O
  2. Setting Up epoll
  3. The Event Loop
  4. A Simple Echo Server
← Back to C Academy