I would like to do the following in a command-line application on OS X:
while (true) {
// do some task
if (user_has_pressed('x')) {
// break out of the loop and do something different
}
}
For clarity, I don't want the program to block waiting for user input. I'm running a numerical simulation that takes many hours to run, and I want to press a key to print detailed statistics on its progress, or interrupt it and change parameters, etc.
There are some existing similar questions, but the answers either suggest a windows-only getch
function, or they switch the terminal into a different input mode. I don't want to do that, because I need to retain the ability to interrupt with ctrl-c
without messing up the terminal.
I don't want to build a Cocoa application, and I don't care about being cross-platform. I'm just looking for the simplest quick-and-dirty way to do it in a command line app that will only ever be run on my own machine.
I guess one option is to use ncurses. From a brief bit of reading it seems like a heavier option than I'd like - but if somebody would post a simple minimal example that accomplishes the above task that would be really helpful.
Are you looking for the following behavior?
#include <pthread.h>
#include <iostream>
static volatile bool keep_running = true;
static void* userInput_thread(void*)
{
while(keep_running) {
if (std::cin.get() == 'q')
{
//! desired user input 'q' received
keep_running = false;
}
}
}
int main()
{
pthread_t tId;
(void) pthread_create(&tId, 0, userInput_thread, 0);
while ( keep_running )
{
//! this will run until you press 'q'
}
(void) pthread_join(tId, NULL);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With