How to get the last key pressed without stopping t

2019-06-07 22:31发布

问题:

Writing an application with command line interface and I would like to know at any time if F1 or ESC or an arrow key is pressed. What is the simplest way of doing this? I would like to avoid using a readline type library.

This is a Linux specific question; the program is not multithreaded.

回答1:

An implementation of kbhit() for Linux is presented in Beginning Linux Programming page 167. You can read it on-line at the link provided.

EDIT: I mention kbhit() because it was posted as a solution before it was made clear that the question related to Linux. Unfortunately the solution has been deleted, which is unfortunate. The principle is that when kbhit() returns non-zero, a subsequent blocking character-oriented read call will not block. This is only true for character oriented input; getchar() and other standard functions that read stdio are typically line-oriented, so block until newline.



回答2:

There is no way to do this in the C standard, but C implementations on various operating systems usually have some extension to do this.

On Windows, you can use getch(). On Linux and Unix, look at this question:

Non-blocking getch(), ncurses

Also, this is the very first question in the "System Dependencies" section in the C FAQ list:

19.1



回答3:

Multiple threads?