Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect closed connection on non blocking socket

Tags:

c

io

sockets

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?

like image 875
Luca Forte Avatar asked May 09 '15 10:05

Luca Forte


1 Answers

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.

like image 162
user207421 Avatar answered Sep 21 '22 07:09

user207421