Skip to content
systemcoding.dev
Networking

Add a descriptor to epoll with epoll_ctl and EPOLL_CTL_ADD

Register a socket with an epoll instance using epoll_ctl(EPOLL_CTL_ADD) and an epoll_event holding EPOLLIN on Linux 6.8 with glibc 2.39.

1 min read
Summarize in AI

This is how a socket becomes visible to an event loop. epoll_ctl() with EPOLL_CTL_ADD registers a descriptor on the interest list, together with the events you want and a value that comes back with each notification.

epoll_add.cc
#include <stdio.h>
#include <sys/epoll.h>
#include <sys/socket.h>

int main(void)
{
    int ep = epoll_create1(0);
    int fd = socket(AF_INET, SOCK_STREAM, 0);

    struct epoll_event ev = { .events = EPOLLIN, .data.fd = fd };
    if (epoll_ctl(ep, EPOLL_CTL_ADD, fd, &ev) < 0) {
        perror("epoll_ctl ADD");
        return 1;
    }
    puts("added");

    if (epoll_ctl(ep, EPOLL_CTL_ADD, fd, &ev) < 0)
        perror("second ADD");
    return 0;
}
Text
added
second ADD: File exists

Adding the same descriptor twice fails with EEXIST, which is the safe way to find a bookkeeping bug. A descriptor that does not support polling, such as a regular file, fails with EPERM. EPOLLERR and EPOLLHUP are always reported and do not need to be requested.

The data field is a union that the kernel returns untouched in epoll_wait(), so you choose between storing the descriptor (data.fd) or a pointer (data.ptr), never both. The interest list is keyed by the pair of descriptor and open file description, a detail that matters after dup(). See epoll_ctl(2).

Taggedcepoll
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.