forked from cryptonotefoundation/cryptonote
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSignalHandler.cpp
executable file
·89 lines (71 loc) · 1.71 KB
/
SignalHandler.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright (c) 2011-2015 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "SignalHandler.h"
#include <mutex>
#include <iostream>
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>
#else
#include <signal.h>
#include <cstring>
#endif
namespace {
std::function<void(void)> m_handler;
void handleSignal() {
static std::mutex m_mutex;
std::unique_lock<std::mutex> lock(m_mutex, std::try_to_lock);
if (!lock.owns_lock()) {
return;
}
m_handler();
}
#if defined(WIN32)
BOOL WINAPI winHandler(DWORD type) {
if (CTRL_C_EVENT == type || CTRL_BREAK_EVENT == type) {
handleSignal();
return TRUE;
} else {
std::cerr << "Got control signal " << type << ". Exiting without saving...";
return FALSE;
}
return TRUE;
}
#else
void posixHandler(int /*type*/) {
handleSignal();
}
#endif
}
namespace Tools {
bool SignalHandler::install(std::function<void(void)> t)
{
#if defined(WIN32)
bool r = TRUE == ::SetConsoleCtrlHandler(&winHandler, TRUE);
if (r) {
m_handler = t;
}
return r;
#else
struct sigaction newMask;
std::memset(&newMask, 0, sizeof(struct sigaction));
newMask.sa_handler = posixHandler;
if (sigaction(SIGINT, &newMask, nullptr) != 0) {
return false;
}
if (sigaction(SIGTERM, &newMask, nullptr) != 0) {
return false;
}
std::memset(&newMask, 0, sizeof(struct sigaction));
newMask.sa_handler = SIG_IGN;
if (sigaction(SIGPIPE, &newMask, nullptr) != 0) {
return false;
}
m_handler = t;
return true;
#endif
}
}