Apache Mesos
posix_signalhandler.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 __POSIX_SIGNALHANDLER_HPP__
14 #define __POSIX_SIGNALHANDLER_HPP__
15 
16 #include <signal.h>
17 
18 #include <functional>
19 #include <mutex>
20 
21 #include <stout/synchronized.hpp>
22 
23 namespace os {
24 namespace internal {
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 std::function<void(int, int)>* signaledWrapper = nullptr;
30 
31 void signalHandler(int sig, siginfo_t* siginfo, void* context)
32 {
33  if (signaledWrapper != nullptr) {
34  (*signaledWrapper)(sig, siginfo->si_uid);
35  }
36 }
37 
38 
39 int configureSignal(const std::function<void(int, int)>* signal)
40 {
41  // NOTE: We only expect this function to be called multiple
42  // times inside tests and `mesos-local`.
43 
44  static std::mutex mutex;
45 
46  synchronized (mutex) {
47  if (signaledWrapper != nullptr) {
48  delete signaledWrapper;
49  }
50 
51  struct sigaction action;
52  memset(&action, 0, sizeof(struct sigaction));
53 
54  signaledWrapper = new std::function<void(int, int)>(*signal);
55 
56  // Do not block additional signals while in the handler.
57  sigemptyset(&action.sa_mask);
58 
59  // The SA_SIGINFO flag tells `sigaction()` to use
60  // the sa_sigaction field, not sa_handler.
61  action.sa_flags = SA_SIGINFO;
62 
63  action.sa_sigaction = signalHandler;
64 
65  return sigaction(SIGUSR1, &action, nullptr);
66  }
67 }
68 
69 } // namespace internal {
70 
71 } // namespace os {
72 
73 #endif // __POSIX_SIGNALHANDLER_HPP__
std::function< void(int, int)> * signaledWrapper
Definition: posix_signalhandler.hpp:29
Definition: posix_signalhandler.hpp:23
#define SIGUSR1
Definition: windows_ctrlhandler.hpp:24
Definition: attributes.hpp:24
void signalHandler(int sig, siginfo_t *siginfo, void *context)
Definition: posix_signalhandler.hpp:31
int configureSignal(const std::function< void(int, int)> *signal)
Definition: posix_signalhandler.hpp:39