Epoll and remote 1-way shutdown
Asked Answered
Q

1

13

Assume a TCP socket on the local linux host is in a connected state with a remote host. The local host is using epoll_wait to be notified of events on the socket with the remote host.

If the remote host were to call:

 shutdown(s,SHUT_WR);

on its connected socket to indicate it is done transmitting, what event(s) will epoll_wait return on the local host for its socket?

I'm assuming EPOLLIN would always get returned and a subsequent recv call would return 0 to indicate the remote side has finished tranmitting.

What about EPOLLHUP or EPOLLRDHUP? (And what is the difference between these two events)?

Or even EPOLLERR ?

If the remote host calls "close" instead of "shutdown", does the answer to any of the above change?

Quizzical answered 3/1, 2012 at 2:59 Comment(0)
Q
23

I'm answering this myself after doing the heavy lifting to find the answer.

A socket listening for epoll events will typically receive an EPOLLRDHUP (in addition to EPOLLIN) event flag upon the remote peer calling close or shutdown(SHUT_WR). This does not neccessarily mean the socket is dead. Subsequent calls to recv() will return any unread data on the socket and eventually "0" will be returned to indicate EOF. It may even be possible to send data back if the remote peer only did a half-close of its socket.

The one notable exception is if the remote peer is using the SO_LINGER option enabled on its socket with a linger value of "0". The result of closing such a socket may result in a TCP RST getting sent instead of a FIN. From what I've read, a connection reset event will generate either a EPOLLHUP or EPOLLERR. (I haven't had time to confirm, but it makes sense).

There is some documentation to suggest there are older Linux implementations that don't support EPOLLRDHUP, as such EPOLLHUP gets generated instead.

And for what it is worth, in my particular case, I found that it is not too interesting to have code that special cases EPOLLHUP or EPOLLRDHUP events. Instead, just treat these events the same as EPOLLIN/EPOLLOUT and call recv() (or send() as appropriate). But pay close attention to return codes returned back from recv() and send().

Quizzical answered 6/1, 2012 at 21:3 Comment(1)
I had more questions about the behavior here, so I did a detailed dive into these interactions: medium.com/where-the-flamingcow-roams/…Remuneration

© 2022 - 2024 — McMap. All rights reserved.