How to write an event loop using ncurses
An event loop can be used to handle user input.
One of the most important types of input to consider is that which is used to exit a program.
Say we have a program that renders text on-screen.
At some point, we want to exit the program.
We need to read a typed character, check that the character is equal to our exit character, and if so, stop our loop and exit the program.
ncurses
provides us with the function getch
, which, as the name suggests, is used to read typed characters.
If we call halfdelay
beforehand, we ensure that getch()
only blocks for an integer amount of tenths of a second.
That’s all we need.
The simplest solution is a while
loop with a condition that fails when our exit character is typed:
halfdelay(1);
/* Event loop */
while(running) {
ch = getch();
if (ch == 'q') {
/* This will cause the while loop to end the */
/* next time the while loop checks the */
/* value of 'running' */
running = false;
}
}
References
The ncurses
documentation, which can be read by running the command man ncurses
inside a terminal.
The ncurses
documentation can be obtained on a Debian system by installing the ncurses-doc
package, or on a CentOS/Redhat/Fedora systems by installing the ncurses-devel
package.