Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Nishtha Thakur

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
$

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.