×

C++ Signal Handling

Signals are interruptions sent by the operating system to a process to cause it to cease doing its current job and focus on the task for which the interrupt was produced. The operating system can also emit signals based on system or error conditions.

There are some signals that the program will not detect, however there is a list below of signals that you may catch in your program and use to take necessary actions.

The following is a list of signals, along with their descriptions and capabilities:

SIGABRTAbnormal program termination, such as a request to abort.
SIGFPEA mistaken arithmetic operation, such as a division by zero or an overflow operation.
SIGILLIt is used to identify erroneous instructions.
SIGINTIt receives an interrupt signal from an interactive program.
SIGSEGVIncorrect storage access.
SIGTERM        A program termination request was issued.
SIGHUPIt reports that the user's terminal is disconnected (POSIX). It is used to indicate that the controlling procedure has ended.
SIGQUITTo end a process and create a core dump, use this command.
SIGTRAPTrap for traces.
SIGBUSThis is a BUS error, indicating that you tried to visit an incorrect address.
SIGUSR1Signal 1 is a user-defined signal.
SIGUSR2Signal 2 is a user-defined signal.
SIGALRMAccess to an incorrect address is shown by an alarm clock.
SIGTERMTermination device.
SIGCOUNTThis signal can be ignored, blocked, or handled.
SIGSTOPThis signal delivered to process to make it proceed.

The function signal ()

Unexpected interruptions or events can be trapped using the signal-handling library's function signal.

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

Parameters:

  • The signal is handled by this function.
  • It describes how to handle the number of signals indicated by sig.

The parameter func defines one of the three methods a programme can handle a signal.

  • SIG DFL (default handling): The signal that is handled by the default action for that signal.
  • Ignore Signal (SIG IGN): The signal is ignored, and the code execution continues even if the signal was not intended.
  • Specific function is defined to handle the signal.
  • It is important to remember that the signal we want to capture should be recorded with the signal function and connected with the signal handling function.

Note: The signal processing function should be of type void.

Return

This function's return type is the same as the type of its parameter func. If this method's request is successful, it provides a reference to the handler function that was in responsibility of processing this signal before the call, if one existed.

Data Races

The term "data race" is undefined. If you call this function in a multi threading software then it will create undefined behavior.

Example to show how to utilize the signal() function:

#include <iostream> 
#Include <bits/sdtc++.h>
#include <stdlib>
#include <csignal>  
using namespace std;  
signal signalled = 0;  
void handler(int signal)  
{  
    signalled = 1;  
}  
int main()  
{  
    sig(SIGINT, handler);  
    raise(SIGINT);  
    if (signalled)  
        cout << "Signal is handled";  
    else  
        cout << "Signal is not handled";  
    return 0;  
}  

OUTPUT:

Signal is handled

Explanation

In the above example in C++, we used data races which is undefined which calls the function in multi threading software.

Another example to show how to utilize the signal() function:

#include <csignal>  
#include <iostream> 
#include <bits/sdtc++.h> 
#include <stdlib>
using namespace  
{  
  volatile std::sig eSignal_Status;  
}  
void signal_handler(int signal)  
{  
  eSignal_Status = signal;  
}  
int main()  
{  
  // Install a signal handler  
  std::signal(SIGINT, signal_handler);  
  std::cout << "Signal_Value: " << eSignal_Status << '\n';  
  std::cout << "Sending_signal " << SIGINT << '\n';  
  std::raise(SIGINT);  
  std::cout << "Signal_Value: " << eSignal_Status << '\n';  
}  

OUTPUT:

Signal_Value: 0
Sending_signal 2
Signal_Value: 2

Explanation

In the above example in C++, we have utilized the signal function which calls the function in multi threading software.

The function race ()

Signals are sent to the currently running application using the C++ signal raise () method.

The raise () method was declared in the < csignal > header file to handle a specific signal.

int raise (int signal);  //syntax

The signal number that should be forwarded for processing. One of the following values can be used:

  • SIGINT
  • SIGABRT
  • SIGFPe
  • SIGILL
  • SIGSeGV
  • SIGTeRM
  • SIGHUP

Return Value

On success, it returns 0; on failure, it returns a non-zero.

Exception

If no function handlers have been specified with signal to handle the raised signal, this function never throws an exception.

Example of a program showing how to utilize the raise () method when SIGABRT is passed:

#include <iostream>
#inlcude <bits/stdc++.h>
#include <stdlib>  
#include <csignal>  
using namespace std;  
signal sig_value = 0;  
void handler(int sig)  
{  
    sig_value = sig;  
}  
int main()  
{  
    signal(SIGABRT, handler);  
    cout << "Before signal handler is called" << endl;  
    cout << "Signal = " << sig_value << endl;   
    raise(SIGABRT);  
    cout << "After signal handler is called" << endl;  
    cout << "Signal = " << sig_value << endl;  
    return 0;  
}  

OUTPUT:

Before signal handler is called
Signal = 0
After signal handler is called
Signal = 6

Explanation

In the above program in C++, we have passed SIGABRT and utilized the raise function by passing SIGABRT and handler in the main function.


Related Topics

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

Name Mangling and extern in C++

Name Mangling and Function Overloading: Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the...

4 minutes read.

Leap Year Program in C++

What is a Leap Year? A solar year is the length of time that it takes for Earth to orbit the Sun - approximately 365.25 days. In a calendar year, we...

4 minutes read.

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

8 minutes read.

C++ Signal Handling

Signals are interruptions sent by the operating system to a process to cause it to cease doing its current job and focus on the task for which the interrupt was...

4 minutes read.

How to Handle Divide by Zero Exception in C++

If you are a programmer or interested in coding then it is obvious that you face some illogical test cases. Suppose, you have written one program that calculates the factorial...

6 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

Fast Input and Output in C++

In competitive programming, it's critical to read input as quickly as possible in order to save time. "Warning: Big I / O data, be aware of certain languages (but most...

3 minutes read.

Auto keyword in C++

The primary function of auto keyword is to assign and detect the value of the data type automatically in C++. The compiler knows the data type of the variable by...

2 minutes read.

Bitmasking in C++

Bitmasking is a technique that is used to access a particular bit within the data bytes. When you apply the iterative approach, this phenomenon is used. A bitmask is described...

6 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.

Sizeof() Operators in C++

sizeof() Operators in C++ The sizeof() operator in C++ defines the size of variables, constants, or data types. It is a unique operator that manipulates other operators and returns the size...

4 minutes read.

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a...

4 minutes read.

System() function in C++

As a part of the c/c+ standard library, the system() function passes commands to be executed by the operating system’s command processor or terminal and returns the completed command. We...

2 minutes read.

Virtual class in C++

Introduction to Virtual Base class Virtual base classes can be utilized in virtual inheritance as a mechanism for examining many "instances" of a certain class while searching through multiple inheritances in...

6 minutes read.

Continue in C++ While loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the...

4 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

Timsort Implementation Using C++

Timsort Implementation Using C++ The Timsort is a stable sorting algorithm that uses the idea of merge sort and insertion sort. It can also be called a hybrid algorithm of insertion...

3 minutes read.

C++ Inline function

A C++ function that extends in line when called is known as an inline function. It reduces function call overhead by having the compiler use the function code rather than...

4 minutes read.