Signal Handling in C++

In this tutorial, we will learn about Signal Handling in C++. 

Signal Handling in C++

What are the signals? Signals are the interrupts delivered by an operating system to a process. These interrupts cause a program to end prematurely. We can generate signals on LINUX, UNIX, MAC OS X or Windows by pressing Ctrl + C. There are various types of signals. A program cannot catch some signals, however, it does catch a few signals. The following header file defines signals that the program can catch in C++.

#include <signal.h>

Here is a list of signals along with their descriptions :

 

SIGABRT

(Signal Abort) Abnormal termination, like a call to abort.

SIGFPE

(Signal Floating-Point Exception) Arithmetic operations with errors, like division by zero.

SIGILL

(Signal Illegal Instruction) Detects illegal instructions

SIGINT

(Signal Interrupt) Recieves Interactive attention signal, usually by a user.

SIGSEGV

(Signal Segmentation Violation) Invalid access to some storage, like to read or write outside of the memory allocation.

SIGTERM

(Signal Termination) A request to terminate the program.

SIGSTOP

(Signal Stop) It stops a process. This signal cannot be ignored or blocked.

SIGBREAK

(Signal Break) Ctrl-Break Sequence

SIGABRT_COMPAT

Same as SIGABRT. This is compatible across all platforms.

The syntax for signal handling is :

void signal(int signal, signal handler function)

Now, we write a program to show signal handling.

Program for Signal Handling in C++

#include <iostream>
#include <signal.h>

using namespace std;

void signalfunc(int num)
{
  cout << "The interrupt : " << num << endl;
  exit(num);
}

int main()
{
  signal(SIGINT, signalfunc);         //registerring signal and signalhandler 

  while (1)             //loop goes on until the signal is encountered
  {
    cout << "signal uninterrupted...\n";
  }
  return 0;
}

Output :

signal uninterrupted...
signal uninterrupted...
The interrupt : 2

Explanation :

In the above program, we define a signal handler function by the name signalfunc(). Also, we use the SIGINT registered signal to terminate the program. In this, the while loop keeps on going and generating the same output, until the interrupt is encountered. When we press Ctrl + C, it generates an interrupt. Therefore, this calls the signal handler function and prints the output ‘The interrupt is : 2’.

Hope this was helpful. Enjoy Coding!

Also learn :

Exception handling in C++

Custom User Defined Exceptions in C++

Leave a Reply

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