I try to use the select function to accept input, but every 2 seconds does something else if the user hasn’t added anything. The code below waits two seconds when the first time () is selected, but after it prints the first message "timeout", it quickly continues to "log out", without waiting for 2 seconds, basically entering into an infinite loop. Does anyone know what the problem is? Thanks for any help.
#include <stdio.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> using namespace std; const int STDIN = 0; int main(int argc, int *argv[]) { struct timeval tv; fd_set readfds, master; tv.tv_sec = 2; tv.tv_usec = 0; FD_ZERO(&readfds); FD_ZERO(&master); FD_SET(STDIN, &readfds); FD_SET(STDIN, &master); string buffer = ""; while(buffer != "quit"){ readfds = master; if(select(STDIN+1, &readfds, NULL, NULL, &tv) == -1) perror("select"); if (FD_ISSET(STDIN, &readfds)){ getline(cin, buffer); cout << "You entered: " << buffer << endl; }else cout << "Timed out.\n" << endl; } return 0; }
source share