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 <sys/signalfd.h> 9 10 #include <map> 11 #include <memory> 12 13 #include <base/callback.h> 14 #include <base/files/file_descriptor_watcher_posix.h> 15 #include <base/files/scoped_file.h> 16 #include <brillo/asynchronous_signal_handler_interface.h> 17 #include <brillo/brillo_export.h> 18 19 namespace brillo { 20 // Sets up signal handlers for registered signals, and converts signal receipt 21 // into a write on a pipe. Watches that pipe for data and, when some appears, 22 // execute the associated callback. 23 class BRILLO_EXPORT AsynchronousSignalHandler final : 24 public AsynchronousSignalHandlerInterface { 25 public: 26 using AsynchronousSignalHandlerInterface::SignalHandler; 27 28 AsynchronousSignalHandler(); 29 ~AsynchronousSignalHandler() override; 30 31 AsynchronousSignalHandler(const AsynchronousSignalHandler&) = delete; 32 AsynchronousSignalHandler& 33 operator=(const AsynchronousSignalHandler&) = delete; 34 35 // Initialize the handler. 36 void Init(); 37 38 // AsynchronousSignalHandlerInterface overrides. 39 void RegisterHandler(int signal, const SignalHandler& callback) override; 40 void UnregisterHandler(int signal) override; 41 42 private: 43 // Called from the main loop when we can read from |descriptor_|, indicated 44 // that a signal was processed. 45 void OnReadable(); 46 47 // Updates the set of signals that this handler listens to. 48 BRILLO_PRIVATE void UpdateSignals(); 49 50 // Map from signal to its registered callback. 51 using Callbacks = std::map<int, SignalHandler>; 52 Callbacks registered_callbacks_; 53 54 // File descriptor for accepting signals indicated by |signal_mask_|. 55 base::ScopedFD descriptor_; 56 57 // Controller used to manage watching of signalling pipe. 58 std::unique_ptr<base::FileDescriptorWatcher::Controller> fd_watcher_; 59 60 // A set of signals to be handled after the dispatcher is running. 61 sigset_t signal_mask_; 62 63 // A copy of the signal mask before the dispatcher starts, which will be 64 // used to restore to the original state when the dispatcher stops. 65 sigset_t saved_signal_mask_; 66 }; 67 68 } // namespace brillo 69 70 #endif // LIBBRILLO_BRILLO_ASYNCHRONOUS_SIGNAL_HANDLER_H_ 71