Menu

C++ TUTORIALS - C++ Signal Handling

C++ Signal Handling

ADVERTISEMENTS

SignalDescription
SIGABRTAbnormal termination of the program, such as a call to abort
SIGFPEAn erroneous arithmetic operation, such as a divide by zero or an operation resulting in overflow.
SIGILLDetection of an illegal instruction
SIGINTReceipt of an interactive attention signal.
SIGSEGVAn invalid access to storage.
SIGTERMA termination request sent to the program.

ADVERTISEMENTS

The signal() function:

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

ADVERTISEMENTS

#include <iostream>
#include <csignal>

using namespace std;

void signalHandler( int signum )
{
    cout << "Interrupt signal (" << signum << ") received.\n";

    // cleanup and close up stuff here  
    // terminate program  

   exit(signum);  

}

int main ()
{
    // register signal SIGINT and signal handler  
    signal(SIGINT, signalHandler);  

    while(1){
       cout << "Going to sleep...." << endl;
       sleep(1);
    }

    return 0;
}

Going to sleep....
Going to sleep....
Going to sleep....

Going to sleep....
Going to sleep....
Going to sleep....
Interrupt signal (2) received.

The raise() function:

int raise (signal sig);

#include <iostream>
#include <csignal>

using namespace std;

void signalHandler( int signum )
{
    cout << "Interrupt signal (" << signum << ") received.\n";

    // cleanup and close up stuff here  
    // terminate program  

   exit(signum);  

}

int main ()
{
    int i = 0;
    // register signal SIGINT and signal handler  
    signal(SIGINT, signalHandler);  

    while(++i){
       cout << "Going to sleep...." << endl;
       if( i == 3 ){
          raise( SIGINT);
       }
       sleep(1);
    }

    return 0;
}

Going to sleep....
Going to sleep....
Going to sleep....
Interrupt signal (2) received.