Lucas
Lucas

Reputation: 77

C Sockets: Avoiding garbage when socket is closed

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?

Upvotes: 5

Views: 1277

Answers (2)

Dave Rager
Dave Rager

Reputation: 8160

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 connection is closed. Always check your return values.

Upvotes: 7

jørgensen
jørgensen

Reputation: 10579

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};

Upvotes: -2

Related Questions