📜 ⬆️ ⬇️

Waiting for character input in unix console

Once again, I ran into the problem of blocking the reading of a character from a unix console. Anyone who had the good fortune to write in borland Pascal under DOS probably remembers the ReadKey() function, which blocks the execution of the program before pressing enikey. I have a couple of times this requirement pops up in the Unix console, but the getchar() function of the block blocks execution before pressing Enter, which is not very desirable in some cases.

 #include <stdio.h> #include <termios.h> #include <unistd.h> int main() { struct termios term; tcgetattr(STDIN_FILENO, &term); term.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, 0, &term); if (getchar()) { printf(«Hello world!»); } return 0; } 

The whole point of the approach is in the termios structure, which describes the terminal parameters. The c_lflag field c_lflag responsible for the so-called local options, i.e. for how the characters will be processed by the driver.

Our enemy in this case is the ICANON bit, which is responsible for choosing the canonical or non-canonical (raw) input mode. The canonical mode for stdin set by default and implies, among other things, a string buffer, i.e. the requirement to press Enter each time you want to feed something getchar() . Accordingly, it is required to transfer stdin to the non-canonical mode.

The ECHO bit of the same termios field is responsible for the input echo, i.e., in this case, the display of the entered character on the screen. We remove / leave to taste.

')

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


All Articles