简体   繁体   中英

recv returns 0 instead of -1 when client crashes

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.

Here's the code:

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

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

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

int receive_message(int descriptor, char* buffer){

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

  return ret;
}

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.

How can I resolve this?

Ok after a research I found how my question is the result of beeing a noob with C socket. Even if the client crashes with no close() function on the socket by the client side, the recv from the server side will return 0 by the way. I thought it will be return -1 or some error. My fault. We can close this and thanks to everyone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM