Please find the section of code below. I want to print the current value of the variable continuously in a loop. And the loop has to be terminated once I hit escape key. Here the problem is that the execution stops at the getchar function. But I want it to continue and print the value of variable until I hit the escape button.
do
{
vUpdateVariable(); // routine to update the current value of variable
printf("Value is %f\r", fVariable);
ucKey = getchar();
usleep(1000);
}while (ucKey != 0x1B);
There are a wide range of ways to do this including that mentioned here however my personal favorite is to use a fork and signal. This is more efficient than non blocking ops (does not waste system calls and thus context switches) on every loop iteration.
Effectively you fork a worker process to perform the loop, install a signal handler for say USR1 into it then have your parent process wait for a keypress blocking, once it receives the wanted key it can send the USR1 signal to the other process which will cause the signal handler to clean it up and terminate.
Please see these for more info:
I shall also note that this solution works for effectively any blocking situation which you could fix using non-blocking IO and will usually save some CPU time, albeit costing a little memory and CPU when creating the fork.
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