How can I exit from an infinite loop, when a key is pressed? Currently I\'m using getch, but it will start blocking my loop as soon, as there is no more input to read.
If you do not want to use non-standard, non-blocking way and yet graceful exit. Use signals and Ctrl+C with user provided signal handler to clean up. Something like this:
#include
#include
#include
/* Signal Handler for SIGINT */
void sigint_handler(int sig_num)
{
/* Reset handler to catch SIGINT next time.
Refer http://en.cppreference.com/w/c/program/signal */
printf("\n User provided signal handler for Ctrl+C \n");
/* Do a graceful cleanup of the program like: free memory/resources/etc and exit */
exit(0);
}
int main ()
{
signal(SIGINT, sigint_handler);
/* Infinite loop */
while(1)
{
printf("Inside program logic loop\n");
}
return 0;
}