C exit from infinite loop on keypress

2019-01-18 14:14发布

问题:

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.

回答1:

I would suggest that you go throgh this article.

Non-blocking user input in loop without ncurses.



回答2:

If you are using getch() from conio.h anyway, try to use kbhit() instead. Note that both getch() and kbhit() - conio.h, in fact - are not standard C.



回答3:

The function kbhit() from conio.h returns non-zero value if any key is pressed but it does not block like getch(). Now, this is obviously not standard. But as you are already using getch() from conio.h, I think your compiler has this.

if (kbhit()) {
    // keyboard pressed
}

From Wikipedia,

conio.h is a C header file used in old MS-DOS compilers to create text user interfaces. It is not described in The C Programming Language book, and it is not part of the C standard library, ISO C nor is it required by POSIX.

Most C compilers that target DOS, Windows 3.x, Phar Lap, DOSX, OS/2, or Win321 have this header and supply the associated library functions in the default C library. Most C compilers that target UNIX and Linux do not have this header and do not supply the library functions.



回答4:

// Include stdlib.h to execute exit function
int char ch;
int i;

clrscr();
void main(){

printf("Print 1 to 5 again and again");
while(1){
for(i=1;i<=5;i++)

     printf("\n%d",i);

    ch=getch();
    if(ch=='Q')// Q for Quit
     exit(0);

    }//while loop ends here

    getch();
    }


回答5:

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 <stdio.h>
#include <signal.h>
#include <stdlib.h>

/* 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;
}