Reputation: 175
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
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:
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
Reputation: 9608
I would recommend the following approach:
This approach uses the time out instead of an separate thread
Upvotes: 0
Reputation: 6001
As @Brady suggested, select() will work
You can also set a socket option
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO ...
Upvotes: 1
Reputation: 7192
Record the current time before the loop starts. On each iteration - check if 5 seconds have passed - if yes - break;
Upvotes: 0