recv returns 0 instead of -1 when client crashes
<p>I have to implement a socket in a multithread linux TCP server who disconnects after a timeout with two setsockopt setted with SO_RCVTIMEO and SO_SNDTIMEO.</p>

<p>Here's the code:</p>

<pre><code>if(setsockopt(receive_sock, SOL_SOCKET, SO_RCVTIMEO, &amp;timeout, sizeof(timeout))&lt;0){
  printf("errore sock option rcvtimeo\n");
  exit(EXIT_FAILURE);
}

if(setsockopt(receive_sock, SOL_SOCKET, SO_SNDTIMEO, &amp;timeout, sizeof(timeout))&lt;0){
  printf("errore sock option sndtimeo\n");
  exit(EXIT_FAILURE);
}
</code></pre>

<p>After the spawning of the thread associated with this socket, the server stays in recv with this function:</p>

<pre><code>int receive_message(int descriptor, char* buffer){

  memset(buffer,0,sizeof(buffer));
  int ret;
  while((ret= recv(descriptor, buffer, BUFFER_SIZE-1, MSG_NOSIGNAL))&lt;=0){
    if (errno == EWOULDBLOCK || errno == EPIPE){
      //stuff...
      pthread_exit(NULL);
    }
    else if (errno == EINTR) continue;
    else exit(EXIT_FAILURE);
  }
  buffer[ret]= '\0';

  return ret;
}
</code></pre>

<p>If the client stays online but with no responses, it will be correctly terminated by the if (errno == EWOULDBLOCK || errno == EPIPE) statement, but if the client crashes or gets terminated, the ret value from the receive will be 0 forever in the while loop instead of -1 or EWOULDBLOCK.</p>

<p>How can I resolve this?</p>