C++ Signal Handling

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

In this C++ tutorial, let us see about Signal handling in C++ with appropriate example programs.

Introduction of Signal Handling

Signals are the interrupts that force an OS to stop its ongoing task and process the task for which the interrupt has been sent. These interrupts can pause an ongoing process in any programs of the operating system. Likewise, C++ allows several signals which can catch and process that in a program. 

Different types of Signals

 Have a look at the list of different signals and their operations in C++.


Abnormal termination of the program, such as a call to abort.


An erroneous arithmetic operation, such as a divide by zero or an operation resulting in overflow.


Detection of an illegal instruction.


Receipt of an interactive attention signal.


Invalid access to storage.


A termination request sent to the program.

The signal() Function

C++ signal-handling library provides signal() function to trap unexpected events.


void (*signal (int sig, void (*func)(int)))(int); 

Program for signal() function

The following C++ program is to catch SIGINT signal using the signal() function.

#include <iostream>
#include <csignal>
using namespace std;
void signalHandler( int signum ) {
   cout << "Interrupt signal (" << signum << ") received.\n";
   // cleanup and close up stuff here  
   // terminate program  
int main () {
   // register signal SIGINT and signal handler  
   signal(SIGINT, signalHandler);  
   while(1) {
      cout << "Going to sleep...." << endl;
   return 0;


Going to sleep....
Going to sleep....
Going to sleep....

Now, press Ctrl+c, program will catch the signal and print as follows.

Going to sleep....
Going to sleep....
Going to sleep....
Interrupt signal (2) received.

Leave a Comment

Your email address will not be published. Required fields are marked *