
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
How do I catch a 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 $
- Related Articles
- How to detect copy paste commands Ctrl+V, Ctrl+C using JavaScript?
- How to fix Ctrl+C inside a Docker container?
- How do I pass an event handler to a component in ReactJS?
- How do I terminate a thread in C++11?
- How do I handle the window close event in Tkinter?
- How do I use arrays in C++?
- How do I use the conditional operator in C/C++?
- How to copy text programmatically (Ctrl+C) in my Android app?
- How do I convert a char to an int in C and C++?
- How do I sort a two-dimensional array in C#
- How do I convert a double into a string in C++?
- Write a program that does not terminate when Ctrl+C is pressed in C
- How do I define string constants in C++?
- How do I generate random floats in C++?
- How do I overload the [] operator in C#?

Advertisements