3
\$\begingroup\$

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 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?

\$\endgroup\$
  • \$\begingroup\$ So, each timeout is 0.1 seconds, and you iterate 100000 times, so you end up waiting for 10000 seconds (3 hours)? \$\endgroup\$ – JS1 Nov 14 '16 at 22:10
  • \$\begingroup\$ No, it only takes about 10 seconds to complete.... I'm not sure of the actual function of the timeout struct. Is this waiting for a user to hit enter after typing something? \$\endgroup\$ – LShaver Nov 15 '16 at 17:40
3
\$\begingroup\$

Must reset timeout

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".

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.