There is a function called select
that can be used for this. It can check if there is new input on a socket to read, and it has a timeout so it can be used for your timer as well.
It exists on one form or other on all major operating systems. Just do a Google search for socket select <your operating system> example
and you will get a boat-load of results.
The last argument to select
is used for the timeout. It's a pointer to a struct timeval
, a structure which contains fields to set the timeout.
If this pointer is passed as NULL
then there is no timeout, and select
can block indefinitely.
To set a timeout, you need to set the tv_sec
field of the timeval
structure to the number of seconds, and the tv_usec
field to the number of microseconds (must be less than one million). You can have a timeout of zero, i.e. just a quick poll, by setting these fields to zero.
If select
returns zero, then there was a timeout.
Example, with a 1.5 second timeout:
for (;;)
{
fd_set readset;
int maxfd;
/* Initialize and set `readset` and `maxfd` */
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 500000;
int res = select(maxfd + 1, &readset, NULL, NULL, &tv);
if (res == -1)
perror("select"); /* Error */
else if (res == 0)
{
/* Timeout, do something */
}
else
{
/* A socket in `readset` is readable */
}
}
If select
returns before the timeout, the timeval
structure is modified to contain the time remaining of the timeout.