
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Catch Ctrl+C Event in C++
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