/* * Toy program to demonstrate use of select for read-with-timeout. * You may use this in your CS143 assignment if you like. * * You can ignore these gcc errors: * timeread.c: In function `timeout': * timeread.c:43: warning: passing arg 2 of `select' from incompatible pointer type * timeread.c:43: warning: passing arg 3 of `select' from incompatible pointer type * timeread.c:43: warning: passing arg 4 of `select' from incompatible pointer type */ #include #include #include #include #include main() { int x; /* * As a demonstration, wait up to 5 seconds for a * line of keyboard input. */ x = timeout(0, 5000); if(x) printf("input available\n"); else printf("timeout\n"); exit(0); } /* * Wait for input to be available on file descriptor fd. But don't * wait longer than ms milliseconds. Return 1 if there is data to * be read on fd, 0 if the timeout expired. */ int timeout(int fd, int ms) { fd_set mask; int n; struct timeval tv; tv.tv_sec = ms / 1000; /* seconds to wait */ tv.tv_usec = (ms % 1000) * 1000; /* and additional microseconds */ FD_ZERO(&mask); FD_SET(fd, &mask); n = select(fd + 1, &mask, (fd_set*)0, (fd_set*)0, &tv); if(n < 0){ perror("select"); exit(1); } return(n); }