Suppose I have a program that infinitely outputs something to the console (for example, the time after its launch). But I need to, when pressing certain keys, the program's action is interrupted and the necessary actions for the given key are performed. Written under ubuntu. The difficulty is that getch (), for example, is waiting for input, but I need the program to continue running all this time. Also, what are the tools for unbuffered I / O in the standard library?

  • Look better towards ncurses or slang - Mike
  • kbhit should go - Qwertiy
  • Are you going to poll the console from time to time or do you want asynchronous notification? / And the second clarification is to respond to each press or is it supposed to enter lines by <Enter>? (@Qwertiy, at least standard (?) In Ubuntu no kbhit ) - avp
  • one
    @Qwertiy Where the TS found getch () is certainly a big question, because neither conio.h nor getch () nor kbhit () in linux is present - Mike

2 answers 2

You road to asynchrony. Try libev. In particular, make a poll of the keyboard through it:

  1. turn off echo
  2. make fd STDIN_FILENO non-blocking
  3. hang the event handler on the libev loop

If you want a crutch. You can only do points 1 and 2, as a result, if the keyboard input (using read(STDIN_FILENO, ch, sizeof(char)); ) is not ready, then -1 will be returned and errno set to EWOULDBLOCK.

Naturally libev can be replaced:

  1. libevent
  2. libuv
  3. Asio
  4. with your decision on select / poll / epoll / kqueue / etc

Turning off echo in the console is googled at a rate of two. You can, for example, look here .

About atexit: https://manned.org/atexit.3 . In short: in the example above it is used to restore the terminal state upon exiting the application and in order not to forget to do it manually.

  • About atexit(reset_input_mode); mention it, otherwise you don’t get to the bottom right away - avp

The easiest way is to process the key combination Ctrl + C. This is done by processing the SIGINT signal. Here is a sample code: https://stackoverflow.com/a/17766999