Here's a complete sample of the select function. User WaitForInput(0) to simulate a poll to stdin.
Code:
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int WaitForInput (int seconds)
{
/*
* Waits n seconds for input.
* returns
* -1 on error
* 0 on no input
* >0 on input available
*
* When seconds == 0, the program will
* wait for a fraction of a second.
*/
fd_set fdset;
struct timeval timeout;
int res;
FD_ZERO(&fdset);
FD_SET(fileno(stdin), &fdset);
timeout.tv_sec = seconds;
timeout.tv_usec = (seconds ? 0 : 100);
res = select(fileno(stdin) + 1, &fdset, 0, 0, &timeout);
switch (res)
{
case -1:
perror ("select");
break;
case 0:
break;
default:
res = FD_ISSET(fileno(stdin), &fdset);
break;
}
return res;
}
int main(void)
{
printf ("Waiting for you to press enter...\n");
if (WaitForInput (1) > 0)
{
puts ("Congrats");
}
else
{
puts ("Too slow!");
}
return 0;
}