/* * 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 ** in Linux, a thread is essentially a light weighted process. When a thread is generated, a corresponding process control structure is generated, * This structure shares the same process memory space with the parent thread's process control structure. At the same time, the process control structure of the new thread will copy the same process information from the parent thread (process) *, such as opening the file list and blocking mask. Because we modified the signal blocking mask * code after the subthread is generated, the subthread uses the original process information of the main thread at this moment, therefore, the subthread will still respond to the SIGINT and sigterm signals. Therefore, when * we use Ctrl + C to send a SIGINT signal, the main process will not process the signal, the sub-process (thread) performs default processing, that is, exit. * When a sub-process exits, it sends a sigchld signal to the parent process (thread), indicating that the sub-process exits. Because the signal is not blocked, * main process (thread) and quit immediately. Therefore, one solution to this problem is to set the signal before the subthread is generated, * or set the signal inside the subthread. * Created on: Aug 14,201 1 * Author: xian0617 */# include <iostream> # include "waitquitsignal. H "sigset_t waitquitsignal: m_wait_mask; struct timespec waitquitsignal: m_time; // call this before thread createvoid waitquitsignal: Init () {try {signal (sigkill, sigign ); sigemptyset (& m_wait_mask); sigaddset (& m_wait_mask, SIGINT); sigaddset (& m_wait_mask, sigquit); sigaddset (& m_wait_mask, sigterm); Aggregate (sig_block, & assign, 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 ;}
Sample Model
int main(int argc ,char **argv){//step1 initWaitQuitSignal::init();//step2 create subthread//step3 wait signalwhile(WaitQuitSignal::wait(flag)){sleep(1);}//step4 deal quit job//save();}