C++ Signal Handling

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++.

  • SIGABRT

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

  • SIGFPE

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

  • SIGILL

Detection of an illegal instruction.

  • SIGINT

Receipt of an interactive attention signal.

  • SIGSEGV

Invalid access to storage.

  • SIGTERM

A termination request sent to the program.

The signal() Function

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

Syntax

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  
   exit(signum);  
}
int main () {
   // register signal SIGINT and signal handler  
   signal(SIGINT, signalHandler);  
   while(1) {
      cout << "Going to sleep...." << endl;
      sleep(1);
   }
   return 0;
}

Output

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 *