Becker
Becker

Reputation: 175

Function work timer

I have a function which receives data from socket, i need to stop function when 5 second passed without creating additional thread. My code:

void TestReceive()
{
 //how to stop code below when 5 second passed&
 size_t received = 0;
 while (received < 4)
 {
  ssize_t r = read(fd, buffer, 4);
  if (r <= 0) break;
  received += r;
 }
}

Upvotes: 0

Views: 154

Answers (4)

Brady
Brady

Reputation: 10357

Use select(), this will block until something is available to read or at most for the time specified in the timeval as below.

int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);

select() does not read or write, what it does is for a set of descriptors (readfds, writefds, and/or exceptfds), it will wait/block until one of the following happens:

  • there is a descriptor ready to be read from
  • there is a descriptor ready to be written to
  • there is an exception on one of the descriptors, like it was closed
  • if the timeout is specified, when the configured time expires

If you just simply need to "wait" (sleep) for 5 seconds, then read, you could sleep (usleep() on linux) for 5 seconds, then do a non-blocking read either by setting the socket options, or call select() with the minimum timeout and check if there is anything to be read.

Here's a related question. How C++ select() function works in Unix OSs?

Upvotes: 2

stefan bachert
stefan bachert

Reputation: 9608

I would recommend the following approach:

  • measure the current time into a var say startTime;
  • LOOP
  • read from your socket USING a timeout (select). Let the timeout to be startTime + 5 sec - now
  • iterate until the timeout has matched (or timeout is to little to apply)

This approach uses the time out instead of an separate thread

Upvotes: 0

nhed
nhed

Reputation: 6001

As @Brady suggested, select() will work

You can also set a socket option setsockopt(s, SOL_SOCKET, SO_RCVTIMEO ...

Upvotes: 1

Ventsyslav Raikov
Ventsyslav Raikov

Reputation: 7192

Record the current time before the loop starts. On each iteration - check if 5 seconds have passed - if yes - break;

Upvotes: 0

Related Questions