| 1 | use std::io; |
| 2 | |
| 3 | use crate::log::dev_warn; |
| 4 | |
| 5 | use super::{SignalNumber, SignalsState, consts::*, set::SignalAction, signal_name}; |
| 6 | |
| 7 | /// A handler for a signal. |
| 8 | /// |
| 9 | /// When a value of this type is dropped, it will try to restore the action that was registered for |
| 10 | /// the signal prior to calling [`SignalHandler::register`]. |
| 11 | pub(crate) struct SignalHandler { |
| 12 | signal: SignalNumber, |
| 13 | original_action: SignalAction, |
| 14 | } |
| 15 | |
| 16 | impl SignalHandler { |
| 17 | const FORBIDDEN: &'static [SignalNumber] = &[SIGKILL, SIGSTOP]; |
| 18 | |
| 19 | /// Register a new handler for the given signal with the provided behavior. |
| 20 | /// |
| 21 | /// # Panics |
| 22 | /// |
| 23 | /// If it is not possible to override the action for the provided signal. |
| 24 | /// If `state` is `Some`, signal changes are tracked and will potentially restored in the |
| 25 | /// future. |
| 26 | /// If `None`, the caller explicitly opts out of restoration. |
| 27 | pub(crate) fn register( |
| 28 | signal: SignalNumber, |
| 29 | behavior: SignalHandlerBehavior, |
| 30 | state: &mut SignalsState, |
| 31 | ) -> io::Result<Self> { |
| 32 | if Self::FORBIDDEN.contains(&signal) { |
| 33 | panic!( |
| 34 | "the {} signal action cannot be overridden", |
| 35 | signal_name(signal) |
| 36 | ); |
| 37 | } |
| 38 | |
| 39 | let action = SignalAction::new(behavior)?; |
| 40 | let original_action = action.register(signal)?; |
| 41 | state.updated(signal)?; |
| 42 | |
| 43 | Ok(Self { |
| 44 | signal, |
| 45 | original_action, |
| 46 | }) |
| 47 | } |
| 48 | |
| 49 | /// Forget this signal handler. |
| 50 | /// |
| 51 | /// This can be used to avoid restoring the original action for the signal. |
| 52 | pub(crate) fn forget(self) { |
| 53 | std::mem::forget(self) |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | impl Drop for SignalHandler { |
| 58 | #[track_caller] |
| 59 | fn drop(&mut self) { |
| 60 | let signal = self.signal; |
| 61 | if let Err(err) = self.original_action.register(signal) { |
| 62 | dev_warn!( |
| 63 | "cannot restore original action for {}: {err}", |
| 64 | signal_name(signal), |
| 65 | ) |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | /// The possible behaviors for a [`SignalHandler`]. |
| 71 | pub(crate) enum SignalHandlerBehavior { |
| 72 | /// Execute the default action for the signal. |
| 73 | Default, |
| 74 | /// Ignore the arrival of the signal. |
| 75 | Ignore, |
| 76 | /// Stream the signal information into the latest initialized instance of [`super::SignalStream`]. |
| 77 | Stream, |
| 78 | /// Store the signal for retrieval with [`super::set::take_first_pending`]. |
| 79 | StorePending, |
| 80 | } |