#include #include #include #include #include #include #include int main() { char buffer[128]; int result, nread; fd_set inputs, inputfds; // sets of file descriptors struct timeval timeout; FD_ZERO(&inputs); // initialize inputs to the empty set FD_SET(0, &inputs); // set file descriptor 0 (stdin) // Wait for input on stdin for a maximum of 2.5 seconds. for (;;) { inputfds = inputs; // 2.5 seconds. timeout.tv_sec = 2; timeout.tv_usec = 500000; // Get select() results. result = select(FD_SETSIZE, &inputfds, (fd_set *) 0, (fd_set *) 0, &timeout); // Check the results. // No input: the program loops again. // Got input: print what was typed, then terminate. // Error: terminate. switch(result) { case 0: { printf("@"); fflush(stdout); break; } case -1: { perror("select"); exit(1); } // If, during the wait, we have some action on the file descriptor, // we read the input on stdin and echo it whenever an // character is received, until that input is Ctrl-D. default: { if (FD_ISSET(0, &inputfds)) { ioctl(0,FIONREAD,&nread); if (nread == 0) { printf("Keyboard input done.\n"); exit(0); } nread = read(0,buffer,nread); buffer[nread] = 0; printf("Read %d characters from the keyboard: %s", nread, buffer); } break; } } } }