Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait only 5 second for user input

Tags:

c

I want to write a simple c program in turbo c++ 4.5 editor such that in only wait 5 seconds for user input. As an example,

#include <stdio.h>

void main()
{
  int value = 0;
  printf("Enter a non-zero number: ");

  // wait only 5 seconds for user input
  scanf("%d",&value);
  if(value != 0) {
    printf("User input a number");
  } else {
    printf("User dont give input");
  }
}

So, what will be the code for 5 seconds wait for 'scanf' functionality and otherwise execute if-else part.

like image 655
user2845121 Avatar asked Dec 20 '22 23:12

user2845121


1 Answers

Try a select(2) loop: https://www.mirbsd.org/man2/select on stdin (fd#0) with a timeout of 5 seconds; run the scanf(3) only if select returns indicating there is data. (See the c_read() function in the mksh source code for an example.)

Other functions, like poll(2), are also possible. Nonblocking I/O is a bit overkill.

OK, here’s a working (on MirBSD) example using select:

#include <sys/types.h>
#include <sys/time.h>
#include <err.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int
main(void)
{
    int value = 0;
    struct timeval tmo;
    fd_set readfds;

    printf("Enter a non-zero number: ");
    fflush(stdout);

    /* wait only 5 seconds for user input */
    FD_ZERO(&readfds);
    FD_SET(0, &readfds);
    tmo.tv_sec = 5;
    tmo.tv_usec = 0;

    switch (select(1, &readfds, NULL, NULL, &tmo)) {
    case -1:
        err(1, "select");
        break;
    case 0:
        printf("User dont give input");
        return (1);
    }

    scanf("%d", &value);
    if (value != 0) {
        printf("User input a number");
    } else {
        printf("User dont give input");
    }
    return (0);
}

You might want to play with the exit codes a bit and sprinkle a few \n throughout the code. The fflush(stdout); is important so that the prompt is shown in the first place…

like image 62
mirabilos Avatar answered Dec 24 '22 01:12

mirabilos