No need to press enter (no block) to read the input key value under Linux

Posted by ramjai on Sat, 04 Apr 2020 12:08:34 +0200

The commonly used input functions scanf and fgets in linux are usually blocking:

1. If the user does not input, the program will block and wait for the user to input, and the user needs to click enter to finish reading the keyboard input.

2. The information entered by the user will be displayed on the screen.  

 

The following code implements:

1. If the user has no input, the program will continue to run after the set time

2. User input information will not be displayed on the screen

3. The program can directly respond to keyboard input without waiting for return

 

 1 #include <stdio.h>                                                                                                                              
 2 #include <stdlib.h>
 3 #include <unistd.h>
 4  
 5 #define TTY_PATH            "/dev/tty"
 6 #define STTY_US             "stty raw -echo -F "
 7 #define STTY_DEF            "stty -raw echo -F "
 8 
 9 #define UNUSED_PARAMTER(X)    (void)(X)
10  
11 static char get_char( void )
12 {
13     fd_set rfds;
14     struct timeval tv;
15     char input_char = 0;
16 
17     FD_ZERO(&rfds);
18     FD_SET(0, &rfds);
19 
20     /**
21      * Set wait time
22      */
23     //tv.tv_sec = 0;    //seconds
24     //tv.tv_usec = 500;  //microseconds
25 
26     /*Check for keyboard input.*/
27     if (select(1, &rfds, NULL, NULL, &tv) > 0)
28         input_char = getchar();
29 
30     return input_char;
31 }
32  
33 char nonblocking_input( void )
34 {
35     char input_char;
36     
37     system(STTY_US TTY_PATH);
38 
39     usleep(100);
40     input_char = get_char();
41 
42     system(STTY_DEF TTY_PATH);
43 
44     return input_char;
45 }
46  
47 int main(int argc, char **argv)
48 {
49     UNUSED_PARAMTER(argc);
50     UNUSED_PARAMTER(argv);
51 
52     char input_char;
53 
54     input_char = nonblocking_input();
55 
56    printf("\n\tYour input is %c!\n", input_char);
57    printf("\nApplication finish.\n\n");
58 
59    return 0;
60 }
test.c

Topics: Linux