1

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Alex Xander
  • 3,903
  • 14
  • 36
  • 43

3 Answers3

5

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

Community
  • 1
  • 1
Thomas Padron-McCarthy
  • 27,232
  • 8
  • 51
  • 75
  • 1
    I don't think that's correct. I suppose you can always do so by writing your own interrupt handlers. – Alex Xander Oct 03 '09 at 09:49
  • 1
    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 Oct 03 '09 at 09:56
  • @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 Oct 03 '09 at 09:56
2

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
  • 88,407
  • 13
  • 85
  • 165
  • 1
    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 Oct 03 '09 at 19:03
1

Multiple threads?

Vlad Gudim
  • 23,397
  • 16
  • 69
  • 92