Linux C++はKill信号、Ctrl+C信号を処理し、安全に退出しやすい


/*
 * WaitQuitSignal.h
 *
 *  Created on: Aug 14, 2011
 *      Author: xian0617
 */

#ifndef WAITQUITSIGNAL_H_
#define WAITQUITSIGNAL_H_
#include <signal.h>
#include <time.h>
class WaitQuitSignal {
public:
	static void init();
	static bool wait(bool&flag);
private:
	static sigset_t m_wait_mask;
	static struct timespec m_time;
};

#endif /* WAITQUITSIGNAL_H_ */
/*
 * WaitQuitSignal.cpp
 *
 * Linux             (light weighted process),                 ,
 *                             。                  (  )
 *             ,               。                     
 *  ,                   ,         SIGINT SIGTERM      ,   
 *    Ctrl+C    SIGINT     ,         ,    (  )       ,   。
 *              (  )  SIGCHLD  ,       ,          ,     
 *    (  )     ,          。                          ,
 *              。
 *  Created on: Aug 14, 2011
 *      Author: xian0617
 */

#include <iostream>
#include "WaitQuitSignal.h"
sigset_t WaitQuitSignal::m_wait_mask;
struct timespec WaitQuitSignal::m_time;
//call this before thread create
void WaitQuitSignal::init(){
 try{
  signal(SIGKILL, SIG_IGN);
  sigemptyset(&m_wait_mask);
  sigaddset(&m_wait_mask, SIGINT);
  sigaddset(&m_wait_mask, SIGQUIT);
  sigaddset(&m_wait_mask, SIGTERM);
  pthread_sigmask(SIG_BLOCK, &m_wait_mask, 0);
 } catch (std::exception& e){
  std::cerr << "exception: " << e.what() << std::endl;
 }
 m_time.tv_sec=0;
 m_time.tv_nsec =0;
}
bool WaitQuitSignal::wait(bool &flag){
 try{
  siginfo_t sig ;
  switch(sigtimedwait(&m_wait_mask,&sig,&m_time)){
  case SIGINT:
  case SIGQUIT:
  case SIGTERM:
   flag=false;
   break;
  default:
   break;
  }

 } catch (std::exception& e){
  std::cerr << "exception: " << e.what() << std::endl;
 }
 return flag;
}