1

I use setsockopt with SO_RCVTIMEO option to set a timeout on my socket recv function. It works, but it instantly closes the socket when time is exceeded. I want to send a message before closing, is it possible ?

(My program have to work on Windows and Linux)

Kevin
  • 2,258
  • 1
  • 32
  • 40
Silta
  • 99
  • 8

2 Answers2

1

I think a reasonable way to implement it is to use select(3) with a timeout. Here is one example: https://smnd.sk/anino/programming/c/unix_examples/poll.html You don't just use recv, but use select() with a timeout parameter.

  fd_set rfd;
  FD_ZERO(&rfd);
  // sock is your socket
  FD_SET(sock, &rfd);
  while (1)
  {
      timeval tv = { 1/*seconds*/, 0 /*ms*/ };
      int result = select(sock+1, &rfd, 0, 0, &tv);
      if (result == EINTR)
      {
          // timeout, send stuff and close(sock)
      }
      else if (result > 0)
      {
          if (!FD_ISSET(sock, &rfd))
          {
             recv(sock, ..);
          }
      }
  }
nulleight
  • 794
  • 1
  • 5
  • 12
1

I have found a method : The socket do the recv() before closing, so I check if the socket recive "" and I can send my message. The socket closing be himself after that.

Silta
  • 99
  • 8