/*************************************************************************
> File Name: SignalHandlerInstallation
> Author: wangzhichen
> Created Time: 2017-01-14
> Statement: install the signal handler
************************************************************************/
#ifndef SIGNAL_HANDLER_INSTALLATION
#define SIGNAL_HANDLER_INSTALLATION
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <vector>
#include <algorithm>
namespace signalhandlerinstallation
{
using namespace std;
class SignalHandlerInstallation
{
private:
struct sigaction m_action;
static SignalHandlerInstallation m_Instance;
private:
SignalHandlerInstallation()
{
m_action.sa_flags = 0;
sigemptyset(&m_action.sa_mask);
}
public:
inline static SignalHandlerInstallation &GetInstance()
{
return m_Instance;
}
void Install(const vector<int>&signums, void (*pHandler)(int) )
{
m_action.sa_handler = pHandler;
for_each(signums.begin(), signums.end(), [this](int signum)
{
sigaction(signum, &m_action, NULL);
});

}
};
SignalHandlerInstallation SignalHandlerInstallation::m_Instance;
}
#endif

/*************************************************************************
> File Name: TermSignalCheck
> Author: wangzhicheng
> Mail: 2363702560@qq.com
> Created Time: 2017-01-14
> Statement: to check whether the terminal signal will come
************************************************************************/
#ifndef TERM_SIGNAL_CHECK
#define TERM_SIGNAL_CHECK
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
namespace termsignalcheck
{
using namespace std;
class TermSignalCheck
{
public:
static bool IsComing;
static void Handler(int signum)
{
cout << "terminated signal is catched...!" << endl;
if(!IsComing) IsComing = true;
}
};
bool TermSignalCheck::IsComing = false;
}
#endif

/*************************************************************************
> File Name: main.cpp
> Author: wangzhicheng
> Mail: 2363702560@qq.com
> Created Time: 2017-01-14
> Statement: testing suit
************************************************************************/
#include <fstream>
#include <thread>
#include "SignalHandlerInstallation.h"
#include "TermSignalCheck.h"
using namespace signalhandlerinstallation;
using namespace termsignalcheck;
void func()
{
ifstream is("./input.data");
if(!is) return;
string line;
while(getline(is, line))
{
cout << "read line = " << line << endl;
if(TermSignalCheck::IsComing) break;
sleep(2);
}
is.close();

}
int main()
{
vector<int>signums_term;
signums_term.push_back(SIGINT);
signums_term.push_back(SIGTERM);
SignalHandlerInstallation::GetInstance().Install(signums_term, TermSignalCheck::Handler);
thread th(func);
th.detach();
sleep(3);
cout << "I am over...!" << endl;
while(1)
{
if(TermSignalCheck::IsComing) break;
sleep(10);
}

return 0;
}

CC=g++
all:
$(CC) -std=c++11 -g -o TestSignalCheck main.cpp SignalHandlerInstallation.h TermSignalCheck.h -pthread -lpthread