Search code examples
c++event-handlingposixsignalssigint

How can I catch a ctrl-c event?


How do I catch a Ctrl+C event in C++?


Solution

  • signal isn't the most reliable way as it differs in implementations. I would recommend using sigaction. Tom's code would now look like this :

    #include <signal.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <unistd.h>
    
    void my_handler(int s){
               printf("Caught signal %d\n",s);
               exit(1); 
    
    }
    
    int main(int argc,char** argv)
    {
    
       struct sigaction sigIntHandler;
    
       sigIntHandler.sa_handler = my_handler;
       sigemptyset(&sigIntHandler.sa_mask);
       sigIntHandler.sa_flags = 0;
    
       sigaction(SIGINT, &sigIntHandler, NULL);
    
       pause();
    
       return 0;    
    }