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.
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.
#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;
}added
second ADD: File existsAdding 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).