简体   繁体   中英

Implementing socket write timeout

Hi I'm trying to know if data wasn't send through the socket after a period of time, I tried to implement it like so:

int write_t(int sock, void *buf, unsigned int len){
  fd_set set;
  struct timeval timeout;
  int rv;

  FD_ZERO(&set);
  FD_SET(sock, &set);

  timeout.tv_sec = RW_TIMEOUT;
  timeout.tv_usec = 0;

  rv = select(sock + 1, &set, NULL, NULL, &timeout);
  if(rv == -1)
    return -1;
  else if(rv == 0)
    return -2;
  else
    return write( sock, (unsigned int *)buf, len );
}

however when I'm using this code the program blocks for timeout.tv_sec seconds and doesn't send anything. What is the problem here? How can I implement write timeout correctly?

Thanks.

You're setting the FD into the readfds , so you're blocking in select until the socket becomes readable, which doesn't happen, so you get the timeout. You should set it into the writefds .

Note that what you're doing doesn't guarantee that the data was actually sent. It guarantees that some data was transferred into the socket send buffer, from whence it will get sent as and when TCP determines, asynchronously to the write.

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