Search code examples
clinuxsocketsepolliocp

Reading a socket asynchronously with `read` and `epoll`


There's something I miss when it comes to epoll

In Win32, If a socket is registered under some IOCP and no data is available for the socket to read, then issuing an asynchronous read action using ReadFile with some overlapped struct will return false and the error code is WSA_IO_PENDING.

When data is available, then the IOCP pulls out the relevant overlapped, the buffer given to ReadFile contains the newly-read-data and you can continue from there.

When it comes to linux and epoll, I don't get it. If you register a socket under some epoll object and no data is available, read will just return -1 and errno is EWOULDBLOCK or EAGAIN. I also understand that monitoring EPOLLIN is semi-helpfull, as EPOLLIN talks about being able to read from the socket, not about actual existing data to read.

how can one tell the socket "hey, I want X bytes of data or less to be written this buffer, If you don't have the data now, it's fine - give it to me when you do. notify me when the data is stored in the buffer"?

Is it possible with an epoll object as it is possible with IOCP?


Solution

  • There is no API that would notify you when X data is available, or buffer reads for you. There are APIs that will unblock when any non-zero amount of data is available. One of these APIs is epoll_wait. You will need to read and collect X data yourself in your buffer.