C select () timeout STDIN single char (no ENTER)

I want to use select() to work with typing a single char (no ENTER) from STDIN.

So, when the user presses one key, select() should immediately return, without waiting for the user to press ENTER.

 int main(void) { fd_set rfds; struct timeval tv; int retval; /* Watch stdin (fd 0) to see when it has input. */ FD_ZERO(&rfds); FD_SET(0, &rfds); /* Wait up to 2 seconds. */ tv.tv_sec = 2; tv.tv_usec = 0; retval = select(1, &rfds, NULL, NULL, &tv); if (retval == -1) perror("select()"); else if (retval) printf("Data is available now.\n"); else printf("No data within five seconds.\n"); exit(EXIT_SUCCESS); } 

This works, but you need to press the ENTER key to finish. I just want the selection to not wait for the user to press the key and ENTER.

Thanks.

+4
source share
2 answers

I believe that when the key is entered into the terminal, it is buffered until you press ENTER, that is, as far as the program is concerned, you have not entered anything. Perhaps you should take a look at this question .

+3
source

In a Unix-style environment, this can be accomplished using the termios functions.

You need to disable canonical mode, which is a terminal function that allows you to edit lines before your program sees the input.

 #include <termios.h> #include <unistd.h> int main(int argc, char **argv) { /* Declare the variables you had ... */ struct termios term; tcgetattr(0, &term); term.c_iflag &= ~ICANON; term.c_cc[VMIN] = 0; term.c_cc[VTIME] = 0; tcsetattr(0, TCSANOW, &term); /* Now the rest of your code ... */ } 

Finding errors that may occur as a result of calls to tcgetattr and tcsetattr remains as an exercise for the reader.

+1
source

Source: https://habr.com/ru/post/1386444/


All Articles