patterncMinor
Waiting for input with timeout
Viewed 0 times
waitingwithinputtimeoutfor
Problem
When my program begins, I want to allow the user to hit a key to enter debug mode for one of the modules. Many of the solutions (involving
This code works, based on a few quick tests, and exhibits the behavior I want. But, have I created any problems for myself?
alarm(), in particular) seemed complicated and involved multiple functions. Instead, I adapted this answer:// Check to see if we should enter GSM de-bug mode
fd_set s;
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 100000;
int i = 100000;
do {
printf("Press [ENTER] for GSM debug mode... %i \r",i/10000);
fflush(stdout);
FD_ZERO(&s);
FD_SET(STDIN_FILENO, &s);
select(STDIN_FILENO+1, &s, NULL, NULL, &timeout);
i--;
} while (FD_ISSET(STDIN_FILENO, &s) == 0 && i > 0);
if ( i <= 0 ) { printf("\nSkipping debug mode...\n"); }
else
{
printf("\nEntering debug mode...\n");
// fill in the debug code here
}This code works, based on a few quick tests, and exhibits the behavior I want. But, have I created any problems for myself?
Solution
Must reset timeout
Once you do that, you no longer need 100000 iterations, because each iteration will have the proper 0.1 second timeout instead of returning "immediately".
select() is allowed to modify your timeout value. So for your program, what happens is that the first call to select() takes 0.1 seconds because of the timeout, but the timeout is then reduced to 0. The next 99999 calls to select() have a zero timeout. You should reset the timeout right before you call select(), like this:timeout.tv_sec = 0;
timeout.tv_usec = 100000;
select(STDIN_FILENO+1, &s, NULL, NULL, &timeout);Once you do that, you no longer need 100000 iterations, because each iteration will have the proper 0.1 second timeout instead of returning "immediately".
Code Snippets
timeout.tv_sec = 0;
timeout.tv_usec = 100000;
select(STDIN_FILENO+1, &s, NULL, NULL, &timeout);Context
StackExchange Code Review Q#147021, answer score: 3
Revisions (0)
No revisions yet.