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?
2 answers
You road to asynchrony. Try libev. In particular, make a poll of the keyboard through it:
- turn off echo
- make fd
STDIN_FILENOnon-blocking - 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:
- libevent
- libuv
- Asio
- 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
kbhitshould go - Qwertiy ♦kbhit) - avp