How to Handle SIGABRT Signal in C++

In C++, SIGABRT short for Signal Abort is a signal used by the abort function to indicate an abnormal program termination. This is commonly used to signal critical errors where continuing the execution of the program is not possible. In this article, we will learn how to handle SIGABRT Signal in C++.

Handling SIGABRT Signal in C++

In C++, the SIGABRT signal is sent to a process when an unrecoverable error occurs, usually due to assertion failure or a call to the abort() function. By default, when a process receives SIGABRT, it prints a message on the console and terminates the program abnormally. However, we can set up custom signal handlers to catch SIGABRT and perform custom actions such as logging required information or cleanup processes before termination of the program.

To handle the SIGABRT signal in C++, we must register a signal handler function using the signal() function provided by the <csignal> header. Following is the syntax to use signal() function in C++:

Syntax

signal(int signum, signal_Handler);

where:

  • signum: specifies the signal number for which the action is being set for example SIGABRT.
  • signal_Handler: name of the signal handler function that will be called when SIGABRT is received.

C++ Program to Handle SIGABRT Signal in C++

The following program demonstrates how we can handle a SIGABRT signal in C++ using the signal function:

C++
// C++ Program to Handle SIGABRT Signal in C++
#include <csignal>
#include <cstdlib>
#include <iostream>
using namespace std;

// Signal handler function for SIGABRT
void handleSigabrt(int signal)
{
    cerr
        << "SIGABRT received. Terminating the Program...\n";

    // Perform any cleanup tasks here
    // optionally holding the program
    int i;
    cin >> i;
}

int main()
{

    // Set up the signal handler for SIGABRT
    signal(SIGABRT, handleSigabrt);

    // Inform the user that the program is running
    cout << "Program running. Send SIGABRT signal to "
            "terminate.\n";

    // send the SIGABRT signal by calling the abort function
    abort();

    // The below code will not be executed
    cout << "This line will not be printed";

    return 0;
}

Output

Program running. Send SIGABRT signal to terminate.
SIGABRT received. Terminating the Program...

Time Complexity: O(1), as the signal function takes constant time.
Auxiliary Space: O(1), as no extra space is used.

Explanation: In the above program, we have manually sent a SIGABRT signal by calling the abort() function to demonstrate how a SIGABRT signal can be handled. As the compilers or systems usually send the SIGABRT signal, it was impossible to illustrate a situation where an actual SIGABRT signal is received.