When recv
returns a value of 0 that means the connection has been closed.
See the recv
man page:
These calls return the number of bytes received, or -1 if an error
occurred.
The return value will be 0 when the peer has performed an orderly
shutdown.
In answer to question #1, yes the socket is now invalid. You must create a new socket and connection for further communications. Edit Now as valdo pointed out below, there is also the possibility of having a half-closed TCP connection in which you can't receive any more but you can keep writing to the socket until you've finished sending your data. See this article for more details: TCP Half-Close. It doesn't sound like you have this situation though.
In answer to question #2, there are basically two ways to detect a closed socket. This assumes that the socket went through an orderly shutdown, meaning the peer called either shutdown
or close
.
The first method is to read from the socket in which case you get a return value of 0. The other method is to write to the socket, which will cause the SIG_PIPE signal to be thrown indicating a broken pipe.
In order to avoid the signal, you can set the MSG_NOSIGNAL
socket option in which case send
would return -1 and set errno
to EPIPE
.