简体   繁体   中英

non-blocking io function instead of cin.get()

I have a c++ console application which has an option to be interrupted by pressing any key (implemented by using kbhit()) and in that case it prints what it has done and exits (or can be left to finish the work(some recording) and still prints feedback). I am making ac# gui application for that console application (I'm calling exe file from c# form) and instead of pressing any key on the keyboard, I am using a "stop" button which sends Environment.NewLine (or "\\n") to the redirected input and in the c++ application I now have to use something different from kbhit() for it to work. I tried using cin.get(), like:

if (kbhit() || (cin.get() > 0))  
    stop_recording=true;  

but cin.get() is a blocking function, and if I want the console application to run to the end it won't close without pressing the stop button. Is there any function similar to cin.get() that actually isn't blocking, or maybe a different way to send "any key" from c# to my console application process?

use _getch() insted of cin.get() . its a blocking command, but by executing it only if ( _kbhit() ) it will return immediately.

You can try to send Ctrl+C to the console process to trigger its break behavior.

You can check named synchronization object if you need to continue - ie in your UI process create named Mutex/Semaphore (with random name) and pass this name to the console process. The console process would check once in a while (instead of kbhit) if it still can acquire Mutex/Semaphore and stop when it no longer can.

The other option as suggested by @Komyg is to dedicate a thread for reading console and check if particular input shows up there.

If you expect more communication between the programs search for IPC "inter-process communication" to see more approaches.

Found a very simple answer here: Simple example of threading in C++ . Credits go to Edward Kmett.
I happened to use boost library in the c++ application so I could use boost threads implementation as well. It was quite simple, this is what my thread function look like:

bool stopped=false;

void inputSent() //
{  
    if (kbhit() || (cin.get() > 0))  
        stopped=true;  

}  

and later in main.cpp:

boost::thread stoppedThread = boost::thread(inputSent);  

After that I just check if stopped==true, and I'm not using stoppedThread.join (I don't know if that's mistake or no, since I don't know when the program ends, if I'm leaving zombie threads behind... maybe someone could enlighten me about that).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM