-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCtrlC.cpp
73 lines (56 loc) · 1.27 KB
/
CtrlC.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include "CtrlC.h"
static CtrlCCallback userCallback = nullptr;
#if defined(_WIN32)
#include <windows.h>
WINBOOL WINAPI CtrlCHandler(DWORD fdwCtrlType)
{
switch(fdwCtrlType)
{
case CTRL_C_EVENT:
case CTRL_CLOSE_EVENT:
if (userCallback)
userCallback();
return TRUE;
default:
break;
}
// Return false to indicate that we aren't handling the signal.
return FALSE;
}
bool SetCtrlCHandler(CtrlCCallback callback)
{
userCallback = callback;
return SetConsoleCtrlHandler(CtrlCHandler, callback ? TRUE : FALSE) != 0;
}
#elif defined(__unix)
#include <signal.h>
#include <unistd.h>
static void CtrlCHandler(int s)
{
if (userCallback)
userCallback();
}
bool SetCtrlCHandler(CtrlCCallback callback)
{
userCallback = callback;
if (callback)
{
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = CtrlCHandler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
return sigaction(SIGINT, &sigIntHandler, nullptr) == 0;
}
else
{
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = SIG_DFL; // Restore default.
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
return sigaction(SIGINT, &sigIntHandler, nullptr) == 0;
}
return false;
}
#else
#error Ctrl-C support not written for this platform yet.
#endif