In my server I check if any socket is ready to read using select() to determine it. As a result in main loop select() is executed every time it iterates.
To test the server I wrote a simple client that sends only one message and then quits. BTW. I use protocol buffers to send information – message means an object of type class Message in this library.
The test session looks like:
select()- server’s socket ready to read
accept()client’s socket- read message from client’s socket
select()- server’s socket not ready to read, client’s one ready
- read message from client’s socket
The last step is wrong because client has already closed connection. As a result protobuf library gets Segmentation fault. I wonder why FD_ISSET says the socket is ready in step 6 when it is closed. How can I check if a socket is closed?
EDIT:
I’ve found how to check if the socket is open
int error = 0;
socklen_t len = sizeof (error);
int retval = getsockopt (socket_fd, SOL_SOCKET, SO_ERROR, &error, &len );
the socket is “readable” if the remote peer closes it, you need to call
recvand handle both the case where it returns an error, and the case where it returns 0, which indicates that the peer shut down the connection in an orderly fashion.Reading the
SO_ERRORsockopt is not the correct way, as it returns the current pending error (from, eg. a non-blockingconnect)