C – Why am I getting EPOLLHUP events on brand new sockets

Why am I getting EPOLLHUP events on brand new sockets… here is a solution to the problem.

Why am I getting EPOLLHUP events on brand new sockets

I have some code that gets an exception when running on a virtual machine for some reason.

The order of initialization is:

s_listen = socket(...)
bind(s_listen, ...)
epoll_ctl(epfd, EPOLL_CTL_ADD, s_listen, ...)
listen(s_listen, SOMAXCONN)

Before calling bind, there is an event loop/thread running and processing events on the epoll file descriptor.

The event loop gets EPOLLHUP before calling listen() on the newly created s_listen socket.

SO MY QUESTION IS, WHY AM I GETTING THE EPOLLHUP EVENT ON A BRAND NEW SOCKET?

When I put epoll_ctl after calling listen(), the error goes away, but if they enter before the socket is added to epoll, does that cause some potential connection events to be missed?

Solution

AS SHOWN IN THE EXAMPLE I IN THE COMMENT, IT SEEMS LIKE YOU CAN’T POLL A SOCKET BEFORE IT’S PROPERLY INITIALIZED, UNLESS YOU WANT TO HANDLE EPOLLHUP.

As for the problem, no, you won’t miss any events. Call listen() and then epoll() the same as you would otherwise have to do (listen() + block accept( ) ); The actual incoming connections between these calls are handled by the kernel and wait until your code processes them.

Related Problems and Solutions