Remove a descriptor with EPOLL_CTL_DEL before closing it
Always call epoll_ctl(EPOLL_CTL_DEL) before close() on Linux 6.8, because a dup()ed descriptor keeps a closed socket registered and sending events.
There is a safer habit than relying on close() to clean up an epoll registration. Closing a descriptor removes it from the interest list only when every duplicate of the open file description is closed, so after dup() or fork() the registration survives.
#include <stdio.h>
#include <unistd.h>
#include <sys/epoll.h>
void drop(int ep, int fd)
{
if (epoll_ctl(ep, EPOLL_CTL_DEL, fd, NULL) < 0)
perror("EPOLL_CTL_DEL");
close(fd);
}(no events are reported for fd after drop returns)Without the explicit delete, a program that did dup(fd) and then close(fd) keeps receiving events for the original registration, but epoll_wait() hands back data.fd with a number that may already belong to a different connection. That is a real source of "data delivered to the wrong client" bugs in servers that reuse descriptor numbers quickly.
Since Linux 2.6.9 the event argument may be NULL for a delete, as the example does; older code passed a dummy structure, and portable code still does so. The call fails with ENOENT if the descriptor is not registered. Events already queued by the kernel can still be returned by an epoll_wait() that was in flight, so guard against stale entries in the batch. See epoll(7).