1 // Copyright 2014 The Chromium OS Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef LIBBRILLO_BRILLO_ASYNCHRONOUS_SIGNAL_HANDLER_H_ 6 #define LIBBRILLO_BRILLO_ASYNCHRONOUS_SIGNAL_HANDLER_H_ 7 8 #include <signal.h> 9 #include <sys/signalfd.h> 10 11 #include <map> 12 13 #include <base/callback.h> 14 #include <base/compiler_specific.h> 15 #include <base/macros.h> 16 #include <base/memory/scoped_ptr.h> 17 #include <base/message_loop/message_loop.h> 18 #include <brillo/asynchronous_signal_handler_interface.h> 19 #include <brillo/brillo_export.h> 20 #include <brillo/message_loops/message_loop.h> 21 22 namespace brillo { 23 // Sets up signal handlers for registered signals, and converts signal receipt 24 // into a write on a pipe. Watches that pipe for data and, when some appears, 25 // execute the associated callback. 26 class BRILLO_EXPORT AsynchronousSignalHandler final : 27 public AsynchronousSignalHandlerInterface { 28 public: 29 AsynchronousSignalHandler(); 30 ~AsynchronousSignalHandler() override; 31 32 using AsynchronousSignalHandlerInterface::SignalHandler; 33 34 // Initialize the handler. 35 void Init(); 36 37 // AsynchronousSignalHandlerInterface overrides. 38 void RegisterHandler(int signal, const SignalHandler& callback) override; 39 void UnregisterHandler(int signal) override; 40 41 private: 42 // Called from the main loop when we can read from |descriptor_|, indicated 43 // that a signal was processed. 44 void OnFileCanReadWithoutBlocking(); 45 46 // Controller used to manage watching of signalling pipe. 47 MessageLoop::TaskId fd_watcher_task_{MessageLoop::kTaskIdNull}; 48 49 // The registered callbacks. 50 typedef std::map<int, SignalHandler> Callbacks; 51 Callbacks registered_callbacks_; 52 53 // File descriptor for accepting signals indicated by |signal_mask_|. 54 int descriptor_; 55 56 // A set of signals to be handled after the dispatcher is running. 57 sigset_t signal_mask_; 58 59 // A copy of the signal mask before the dispatcher starts, which will be 60 // used to restore to the original state when the dispatcher stops. 61 sigset_t saved_signal_mask_; 62 63 // Resets the given signal to its default behavior. Doesn't touch 64 // |registered_callbacks_|. 65 BRILLO_PRIVATE void ResetSignal(int signal); 66 67 // Updates the set of signals that this handler listens to. 68 BRILLO_PRIVATE void UpdateSignals(); 69 70 DISALLOW_COPY_AND_ASSIGN(AsynchronousSignalHandler); 71 }; 72 73 } // namespace brillo 74 75 #endif // LIBBRILLO_BRILLO_ASYNCHRONOUS_SIGNAL_HANDLER_H_ 76