5

I'm programming a server and a client using non blocking sockets (fd_sets and select function) and once the server closes or shuts down a client socket, the client starts receiving a lot of garbage until it crashes.. I've been warned that when working with select() a socket would become readable when the connection was terminated, but how can I know in

if( FD_ISSET( socket, &read ) ) 
{
} 

if the cause is just regular data or the connection has ended?

Thank you a lot!

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
Lucas
  • 77
  • 6

2 Answers2

6

The file descriptor sets wont tell you if the socket is closed, only that you may attempt to read from it. When the remote end closes the connection the socket will become "readable". When you attempt a recv() the return value will be 0 indicating the socket is closed. Always check your return values.

Dave Rager
  • 8,002
  • 3
  • 33
  • 52
  • Thanks! So, recv() returns 0 when socket is closed? Haha, that was so obvious.. thanks a lot – Lucas May 09 '11 at 13:28
  • @Lucas Hi ! Welcome to Stackoverflow. If you are satisfied with Dave's answer, you are encouraged to accept it, and maybe upvoting it. Cheers ! – Calvin1602 May 09 '11 at 13:43
  • Thanks! I've signed up and I'll be able to vote answers as soon as I get some rep points – Lucas May 09 '11 at 13:53
0

You will have to use poll instead (it's also more flexible because it's not bound by the size of FD_SET!)

struct poll p = {.fd = fd, .events = POLLHUP|POLLRDHUP};
jørgensen
  • 10,149
  • 2
  • 20
  • 27