C++ Signal Handling


In C++ Signals are software interrupts delivered to a process by the operating system.

To pressing Ctrl+C helps to generate interrupts on Unix, Linux, and windows system.


The following list of signals which you can catch in your program.


Signal Description
SIGABRT This signal helps to abnormal termination of the program, such as a call to abort.
SIGILL This signal helps to detection of an illegal instruction.
SIGFPE This signal helps to an erroneous arithmetic operation, such as a divide by zero or an operation resulting in overflow.
SIGINT This signal helps to receipt of an interactive attention signal.
SIGSEGV This signal helps to invalid access to storage.
SIGTERM This signal helps to termination request sent to the program.
SIGCOUNT This signal sent to process to make it continue.

The signal() Function

The signal() function provides a function signal to trap unexpected events through the signal-handling library.

Syntax:

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

The signal() function had two arguments:

  • An integer which represents the signal number.
  • A pointer to the signal-handling function.

The raise() Function

The raise() function helps to send the signal which takes an integer signal number.

Syntax:

int raise (signal sig);

sig is the signal number to send following one of the signals:

SIGINT, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGTERM, SIGHUP.


Example:

#include <iostream>
#include <csignal>
using namespace std;

sig_atomic_t signalled = 0; 
void handler( int signalnumber ) 
{
    cout << "Interrupt signal (" << signalnumber << ") received.\n";
    signalled=1;     
}
int main () {
    // register signal SIGINT and signal handler  
    signal(SIGINT, handler);  
    raise(SIGINT); 
    if (signalled)  
        cout << "Signal is handled";  
    else  
        cout << "Signal is not handled";  
    return 0;
}



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.