C exit from infinite loop on keypress

前端 未结 5 974
囚心锁ツ
囚心锁ツ 2020-12-10 05:47

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.

5条回答
  •  再見小時候
    2020-12-10 06:28

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

提交回复
热议问题