×

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

Pointers in C++

Pointers are a powerful feature in the C++ programming language, allowing developers to directly manipulate memory addresses and create more efficient and dynamic programs. However, pointers can also source various...

3 minutes read.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.

Octal to Decimal in C++

We need to write a system that converts octal number into equal decimal number when octal number is given as input. Let us look at an example of a program in...

2 minutes read.

Remove duplicates from sorted array in C++

Remove duplicates from the sorted array in C++. This same process, due to a sorted array, is to erase the redundant components from the array. Examples: Input  : arr[] = {2, 2, 2,...

4 minutes read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

For Loop Examples in C++

For Loop A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax of for loop In C++, a...

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

Structure of C++ Program

Many people believe that C++, an object-oriented programming (OOP) language, is the finest language for developing demanding applications. A superset of the C language is C++. Java, a closely comparable...

4 minutes read.

Char Array to String in C++

Regardless of the programming language you use, data structure is critical to the success of your project. Although each programming language has its own collection of data structures, C++ contains a...

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

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

C++ Program For FCFS (First Come First Serve)

The most basic scheduling technique is FCFS, often known as "FIFO (First In, First Out)". In this procedure, the first one is utilized and executed first, while the second one...

4 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

RTTI (Run-Time Type Information) in C++

In C++, RTTI or Run-Time Type Information reveals information about the data type of an object at runtime and only works with classes that have at least one virtual function....

3 minutes read.

C++ Identifier

In a program, C++ identifiers relate to the names of variables, functions, arrays, and other user-defined data types that the programmer has developed. They are a prerequisite for learning any...

4 minutes read.

C++ operator

In this article, we will discuss about the operators in C++ with their types and examples. An operator is specially a symbol that tells compiler to perform specific manipulation. C++ contains...

5 minutes read.

C++ Inheritance

What do you mean by Inheritance ? The ability to define new classes based on existing classes in order to reuse and organise code is referred to as inheritance. Single inheritance...

7 minutes read.

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

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

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 minutes read.