1 // ConsoleClose.cpp 2 3 #include "StdAfx.h" 4 5 #include "ConsoleClose.h" 6 7 #ifndef UNDER_CE 8 9 #ifdef _WIN32 10 #include "../../../Common/MyWindows.h" 11 #else 12 #include <stdlib.h> 13 #include <signal.h> 14 #endif 15 16 namespace NConsoleClose { 17 18 unsigned g_BreakCounter = 0; 19 static const unsigned kBreakAbortThreshold = 2; 20 21 #ifdef _WIN32 22 HandlerRoutine(DWORD ctrlType)23static BOOL WINAPI HandlerRoutine(DWORD ctrlType) 24 { 25 if (ctrlType == CTRL_LOGOFF_EVENT) 26 { 27 // printf("\nCTRL_LOGOFF_EVENT\n"); 28 return TRUE; 29 } 30 31 g_BreakCounter++; 32 if (g_BreakCounter < kBreakAbortThreshold) 33 return TRUE; 34 return FALSE; 35 /* 36 switch (ctrlType) 37 { 38 case CTRL_C_EVENT: 39 case CTRL_BREAK_EVENT: 40 if (g_BreakCounter < kBreakAbortThreshold) 41 return TRUE; 42 } 43 return FALSE; 44 */ 45 } 46 CCtrlHandlerSetter()47CCtrlHandlerSetter::CCtrlHandlerSetter() 48 { 49 if (!SetConsoleCtrlHandler(HandlerRoutine, TRUE)) 50 throw "SetConsoleCtrlHandler fails"; 51 } 52 ~CCtrlHandlerSetter()53CCtrlHandlerSetter::~CCtrlHandlerSetter() 54 { 55 if (!SetConsoleCtrlHandler(HandlerRoutine, FALSE)) 56 { 57 // warning for throw in destructor. 58 // throw "SetConsoleCtrlHandler fails"; 59 } 60 } 61 62 #else // _WIN32 63 HandlerRoutine(int)64static void HandlerRoutine(int) 65 { 66 g_BreakCounter++; 67 if (g_BreakCounter < kBreakAbortThreshold) 68 return; 69 exit(EXIT_FAILURE); 70 } 71 CCtrlHandlerSetter()72CCtrlHandlerSetter::CCtrlHandlerSetter() 73 { 74 memo_sig_int = signal(SIGINT, HandlerRoutine); // CTRL-C 75 if (memo_sig_int == SIG_ERR) 76 throw "SetConsoleCtrlHandler fails (SIGINT)"; 77 memo_sig_term = signal(SIGTERM, HandlerRoutine); // for kill -15 (before "kill -9") 78 if (memo_sig_term == SIG_ERR) 79 throw "SetConsoleCtrlHandler fails (SIGTERM)"; 80 } 81 ~CCtrlHandlerSetter()82CCtrlHandlerSetter::~CCtrlHandlerSetter() 83 { 84 signal(SIGINT, memo_sig_int); // CTRL-C 85 signal(SIGTERM, memo_sig_term); // kill {pid} 86 } 87 88 #endif // _WIN32 89 90 /* 91 void CheckCtrlBreak() 92 { 93 if (TestBreakSignal()) 94 throw CCtrlBreakException(); 95 } 96 */ 97 98 } 99 100 #endif 101