Apache Mesos
windows_ctrlhandler.hpp
Go to the documentation of this file.
1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License at
4 //
5 // http://www.apache.org/licenses/LICENSE-2.0
6 //
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
12 
13 #ifndef __WINDOWS_CTRLHANDLER_HPP__
14 #define __WINDOWS_CTRLHANDLER_HPP__
15 
16 #include <functional>
17 #include <mutex>
18 
19 #include <stout/synchronized.hpp>
20 
21 namespace os {
22 namespace internal {
23 
24 #define SIGUSR1 100
25 
26 // Not using extern as this is used only by the executable. The signal
27 // handler should be configured once. Configuring it multiple times will
28 // overwrite any previous handlers.
29 static std::function<void(int, int)>* signaledWrapper = nullptr;
30 
31 inline BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
32 {
33  switch (fdwCtrlType) {
34  // Handle the CTRL-C signal.
35  case CTRL_C_EVENT:
36  case CTRL_CLOSE_EVENT:
37  case CTRL_BREAK_EVENT:
38  case CTRL_LOGOFF_EVENT:
39  case CTRL_SHUTDOWN_EVENT: {
40  if (signaledWrapper != nullptr) {
41  (*signaledWrapper)(SIGUSR1, 0);
42  return TRUE;
43  }
44  }
45  default: {
46  return FALSE;
47  }
48  }
49 }
50 
51 
52 inline int installCtrlHandler(const std::function<void(int, int)>* signal)
53 {
54  // NOTE: We only expect this function to be called multiple
55  // times inside tests and `mesos-local`.
56 
57  static std::mutex mutex;
58 
59  synchronized (mutex) {
60  if (signaledWrapper != nullptr) {
61  delete signaledWrapper;
62  }
63 
64  if (signal != nullptr) {
65  signaledWrapper = new std::function<void(int, int)>(*signal);
66  return SetConsoleCtrlHandler(CtrlHandler, TRUE);
67  } else {
68  delete signaledWrapper;
69  signaledWrapper = nullptr;
70  return SetConsoleCtrlHandler(CtrlHandler, FALSE);
71  }
72  }
73 }
74 
75 } // namespace internal {
76 
77 } // namespace os {
78 
79 #endif // __WINDOWS_CTRLHANDLER_HPP__
BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
Definition: windows_ctrlhandler.hpp:31
std::function< void(int, int)> * signaledWrapper
Definition: posix_signalhandler.hpp:29
Definition: posix_signalhandler.hpp:23
#define SIGUSR1
Definition: windows_ctrlhandler.hpp:24
int installCtrlHandler(const std::function< void(int, int)> *signal)
Definition: windows_ctrlhandler.hpp:52
Definition: attributes.hpp:24