开发者

C Sockets: Avoiding garbage when socket is closed

I'm programming a server and a client using non blocking so开发者_开发问答ckets (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!


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜