tags:

views:

780

answers:

2

Is there any way to check if a socket has disconnected on the remote end without select() in C?

The reason I don't want to use select() is that in the case that my buffers are full, there may be data available for reading on the socket that I am intentionally ignoring and a select(readfds=[socket_fd]) would always return immediately letting me know.

+4  A: 

If you have a blocking read() function call on the socket, and it returns the integer value 0, that means the socket connection is closed.

while ( n = read(sockfd, buffer, BUFFER_SIZE) ) {
     //use buffer contents
}

This loop will continue while data is being sent from the other end.

ghills
+1  A: 

So use poll() instead, setting events to the things you care about and checking the results in revents. FYI, you can call select() or poll() without harming the sockets or changing their buffers.

dwc
I have some problems when using poll() like this, revents never contains POLLHUP when the socket hangs up, just POLLIN which can't be true.
unexist
See http://www.greenend.org.uk/rjk/2001/06/poll.html for some nice info about this issue.
dwc