Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch a ctrl-c event?

People also ask

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

The CTRL + C is one signal in C or C++. So we can catch by signal catching technique. For this signal, the code is SIGINT (Signal for Interrupt). Here the signal is caught by signal() function.

How do you capture Ctrl-C in Python?

You can handle CTRL + C by catching the KeyboardInterrupt exception. You can implement any clean-up code in the exception handler.

Why is Ctrl-C interrupt?

In graphical user interface environments that use the control key to control the active program, control+C is often used to copy highlighted text to the clipboard. In many command-line interface environments, control+C is used to abort the current task and regain user control.

How do you get a SIGINT signal?

When Ctrl+C is pressed, SIGINT signal is generated, we can catch this signal and run our defined signal handler.


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

For a Windows console app, you want to use SetConsoleCtrlHandler to handle CTRL+C and CTRL+BREAK.

See here for an example.


You have to catch the SIGINT signal (we are talking POSIX right?)

See @Gab Royer´s answer for sigaction.

Example:

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>

void my_handler(sig_t s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{
   signal (SIGINT,my_handler);

   while(1);
   return 0;

}

Yeah, this is a platform dependent question.

If you are writing a console program on POSIX, use the signal API (#include <signal.h>).

In a WIN32 GUI application you should handle the WM_KEYDOWN message.