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

大兔子大兔子 提交于 2019-12-12 05:19:13

问题


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?


回答1:


You should read up on VT100 escape sequences.

You've discovered that the character code for the escape button (which is sent as a real character, but tends to be used almost exclusively for signalling the beginning of an escape sequence) is 0x1b.

To move the cursor UP:    <ESC>[{COUNT}A
To move the cursor DOWN:  <ESC>[{COUNT}B
To move the cursor RIGHT: <ESC>[{COUNT}C
To move the cursor LEFT:  <ESC>[{COUNT}D

You can test these yourself by typing them into the terminal. Just type the keys one after another. My terminal does not recognize the count argument, but will work successfully if I type <ESC>[X (for X in A,B,C,D).

If your terminal isn't in VT100 mode, look up the escape sequences for whichever mode it's in. You might realize that depending too much on terminal specific escape codes restricts your program to one specific terminal type.



来源:https://stackoverflow.com/questions/17838339/is-there-a-typeahead-buffer-for-key-presses-in-linux-terminal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!