views:

343

answers:

3

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 readline type library.

Edited: Linux specific question. It is not multithreaded

+5  A: 

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:

http://stackoverflow.com/questions/905060/non-blocking-getch-ncurses

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

19.1

Thomas Padron-McCarthy
I don't think that's correct. I suppose you can always do so by writing your own interrupt handlers.
Alex Xander
Second that !!!
AJ
Alex: There is no way in the C standard to get key presses to start sending signals, so you can't write a signal handler to do this. Perhaps you are thinking about how to do it in some specific operating system, such as Windows? But as I said, there is nothing in the C standard about it.
Thomas Padron-McCarthy
@Alex Xander: It sounds like you're writing an application level program instead of a device driver, so interrupt handlers are not generally available as an option.
Greg Hewgill
+1  A: 

Multiple threads?

Totophil
I was about to say this ...
Ben
NO It is not multithreaded.
Alex Xander
If you just want to check if a key is pressed, an extra thread would be overkill and complicate things unnecessarily.
Thomas Padron-McCarthy
I think he meant it could be a solution to your problem ....
Ben
+2  A: 

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.

Clifford
I saw the code but it is a blocking call.
Alex Xander
Then you misunderstand the code! kbhit() id non-blocking, and peeks the buffer to see if there is a character available, when it returns non-zero, a subsequent blocking read is then guaranteed *not* to block. Unfortunately the post showing how kbhit() is used (and which I was referring to) has been deleted, presumably because it was not intended for Linux. IMO it should be undeleted, it is still relevant.
Clifford