5
votes

I'm really sorry if my question is a duplicate, but I didn't find useful infos in the site.

I'm using non blocking sockets and a select(). How can I detect if a client closed the connection on non-blocking socket? I saw that a read() returns -1 with errno = EWOULDBLOCK when no datas are available to be read and also when a connection is closed.

How can I discriminate above cases?

2

2 Answers

4
votes

When the peer has closed the connection:

  1. select() will return the socket as readable.
  2. A recv() or read() on the socket will return zero.

I saw that a read() returns -1 with errno = EWOULDBLOCK when no datas are available to be read

Correct, but the connection isn't closed.

and also when a connection is closed.

No you didn't. That's not correct. It returns zero.

How can I discriminate above cases?

They aren't the same, and they don't manifest themselves in the same way.

1
votes

When the peer had closed the connection for a specific socket, a call to read() on this socket would return 0. This behaviour is independent from the socket's blocking state.

From man 2 read (italics by me):

RETURN VALUE

On success, the number of bytes read is returned (zero indicates end of file)