Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a variable continuously in a loop and terminate with a hit of escape key in C under linux? [duplicate]

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);  
like image 540
SilentCat Avatar asked Nov 02 '22 04:11

SilentCat


1 Answers

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:

  • http://linux.die.net/man/2/fork
  • http://man7.org/linux/man-pages/man7/signal.7.html

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.

like image 96
Vality Avatar answered Nov 15 '22 05:11

Vality