Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I interrupt a loop with a key press in C++ on OS X?

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.

like image 406
N. Virgo Avatar asked Dec 01 '16 05:12

N. Virgo


1 Answers

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;
   }
like image 92
Bharath Avatar answered Sep 24 '22 17:09

Bharath