Sunday 31 March 2013

C++ signal handler example

Here is a C++ class implementation to handle signals on unix and linux. A common usage of signal handlers is to allow an application to close down properly (close database connections, write buffers to files etc) when a kill signal is received it can be useful to include a handler for SIGINT and SIGTERM.

Class definition SigHandler.h :
class SigHandler
{
public:
    SigHandler();
    ~SigHandler();
    
    bool setSignalToHandle(int sig);
    static bool isSignalSet();    
    static void setSignal(int unused);
    
private:
    static bool m_signalSet;
    
};

Implenentation SigHandler.cpp:
#include "SigHandler.h"
#include "signal.h"

using namespace std;

bool SigHandler::m_signalSet = false;

SigHandler::SigHandler()
{
}

SigHandler::~SigHandler()
{
}

bool SigHandler::setSignalToHandle(int sig)
{
    if(signal(sig, SigHandler::setSignal) == SIG_ERR) {
        return false;
    }
    return true;
}

void SigHandler::setSignal(int unused)
{
    m_signalSet = true;
}

bool CxmlSigHandler::isSignalSet()
{
    return m_signalSet;
}

A method is required to handle the signal and must return void and take an int parameter.

static void setSignal(int unused);

This is registered with the signal function from signal.h and is invoked whenever the signal is triggered.
bool SigHandler::setSignalToHandle(int sig)
{
    if(signal(sig, SigHandler::setSignal) == SIG_ERR) {
        return false;
    }
    return true;
}

Whenever the signal "sig" is encountered this method is called and will set our flag to true.

Below is a simple example which will loop until a SIGTERM is encountered (generated by kill command):

SigHandler      sigHandler;
sigHandler.setSignalToHandle(SIGTERM); //register SIGTERM to be handled

while(!sigHandler.isSignalSet() { //loop until signal received
    //do stuff here
}

For reference: signal.h

No comments:

Post a Comment