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

C++Server Side ProgrammingProgramming

The CTRL + C is used to send an interrupt to the current executing task. In this program, we will see how to catch the CTRL + C event using 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. Then one callback address is passed to call function after getting the signal.

Please see the program to get the better idea.

Example

#include <unistd.h>
#include <iostream>
#include <cstdlib>
#include <signal.h>
using namespace std;
// Define the function to be called when ctrl-c (SIGINT) is sent to process
void signal_callback_handler(int signum) {
   cout << "Caught signal " << signum << endl;
   // Terminate program
   exit(signum);
}
int main(){
   // Register signal and signal handler
   signal(SIGINT, signal_callback_handler);
   while(true){
      cout << "Program processing..." << endl;
      sleep(1);
   }
   return EXIT_SUCCESS;
}

Output

$ g++ test.cpp
$ ./a.out
Program processing...
Program processing...
Program processing...
Program processing...
Program processing...
Program processing...
^CCaught signal 2
$
raja
Published on 07-May-2019 12:41:27
Advertisements