Home:ALL Converter>Is there a typeahead buffer for key presses in Linux terminal?

Is there a typeahead buffer for key presses in Linux terminal?

Ask Time:2013-07-24T23:22:34         Author:anatoly techtonik

Json Formatter

Does Linux buffer keys typed in terminal so that you can read them later one key at a time?



I am asking because I want to catch ESC and arrow key presses and can't find a way to reliably read the codes. I put terminal in non-canonical mode and want program to block if there is no input, but if there is, I want to fetch only one key press for processing.

Update 2: Arrow keys is just an example. I need to identify key presses even for the keys with unknown escape sequences for my program.

There are two conflicting cases:

  • read(1) returns one character. For both function keys and ESC key this character will be 0x1b. To check if it was an arrow key, you need to read(1), which will block if only single ESC is pressed.
    Solution: blocked read(1), non-blocked read(1)
    Problem: if second read didn't match any function key, it may mean that it was buffered ESC followed by some sequence, or an unknown function key. How to detect unknown function key press?

  • read(4) returns at most 4 characters, but if you press ESC four times to let it buffer, you'll get a string of four 0x1b. The same problem to find out if there is an unknown function key press as above.

Can anybody explain how to deal with these problems in Linux terminal, or at least post a proof that Linux just doesn't have input buffer for keys?

Author:anatoly techtonik,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/17838339/is-there-a-typeahead-buffer-for-key-presses-in-linux-terminal
yy