/*
 * selectsample --- sample piece of code to show how to use select to detect
 *	input on a socket/file descriptor while employing a timeout
 */

#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>

int WaitForInput(int, int);

main()
{
    char buf[128];
    int ret, cnt;

    /* test with file descriptor 0 (stdin) and 5 second timeout */
    printf("Please enter input, you have 5 seconds:\n");
    ret = WaitForInput(0, 5);
    if (ret < 0) {
	printf("Error occured in waiting!\n");
	exit(1);
    }
    else if (ret == 0) {
	printf("timeout occurred, sorry\n");
	exit(1);
    }
    else {  /* ret > 0, must be input available to read */
	cnt = read(0, buf, 128);
	write(1, buf, cnt);	/* write to stdout */
    }
}

/*
 * WaitForInput --- wait for input on the given file descriptor (or socket)
 *	with the given timeout in seconds
 */
int WaitForInput(int fdIn, int timeout)
{
    fd_set bvfdRead;
    struct timeval tv;

    tv.tv_sec = timeout;	/* put timeout secs into timeval struct */
    tv.tv_usec = 0;
    FD_ZERO(&bvfdRead);
    FD_SET(fdIn, &bvfdRead);	   /* fd to look for input */
    /* size of bitmap to watch is one more than value of fdIn */
    return(select(fdIn+1, &bvfdRead, 0, 0, &tv));
}


