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;
}
}
Use select(), this will block until something is available to read or at most for the time specified in the timeval as below.
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?