Search code examples
cwinapimingw32

How to prevent Console Application from terminating when pressing "Ctrl+C" in C?


I found that Console Application compiled from GCC on Windows always terminate when pressing Ctrl+C.

Is there any feasible way to prevent Console Application from terminating when pressing Ctrl+C?


Solution

  • When the user presses control C, a signal (SIGINT) is sent to your process. When most signals are sent to a process, that process must either handle the signal or the operating system will kill it. So... all you need to do is install a signal handler for SIGINT.

    The following is untested:

    #include <signal.h>
    static void ignore_control_c(int sig)
    {
        /* re-arm the signal handler but otherwise ignore the signal */
        signal(sig, ignore_control_c);
    }
    
    int main(int argc, char *argv)
    {
       signal(SIGINT, ignore_control_c);
       ...