Debian Codegraph @

src/sources/signals.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 //! Event source for tracking Unix signals
2 //!
3 //! Only available on Linux.
4 //!
5 //! This allows you to track and receive Unix signals through the event loop
6 //! rather than by registering signal handlers. It uses `signalfd` under the hood.
7 //!
8 //! The source will take care of masking and unmasking signals for the thread it runs on,
9 //! but you are responsible for masking them on other threads if you run them. The simplest
10 //! way to ensure that is to setup the signal event source before spawning any thread, as
11 //! they'll inherit their parent signal mask.
12
13 use std::convert::TryFrom;
14 use std::os::raw::c_int;
15
16 use nix::sys::signal::SigSet;
17 pub use nix::sys::signal::Signal;
18 pub use nix::sys::signalfd::siginfo;
19 use nix::sys::signalfd::{SfdFlags, SignalFd};
20
21 use super::generic::Generic;
22 use crate::{EventSource, Interest, Mode, Poll, PostAction, Readiness, Token, TokenFactory};
23
24 /// An event generated by the signal event source
25 #[derive(Copy, Clone, Debug)]
26 pub struct Event {
27 info: siginfo,
28 }
29
30 impl Event {
31 /// Retrieve the signal number that was receive
32 pub fn signal(&self) -> Signal {
33 Signal::try_from(self.info.ssi_signo as c_int).unwrap()
34 }
35
36 /// Access the full `siginfo_t` associated with this signal event
37 pub fn full_info(&self) -> siginfo {
38 self.info
39 }
40 }
41
42 /// An event source for receiving Unix signals
43 #[derive(Debug)]
44 pub struct Signals {
45 sfd: Generic<SignalFd>,
46 mask: SigSet,
47 }
48
49 impl Signals {
50 /// Create a new signal event source listening on the specified list of signals
51 pub fn new(signals: &[Signal]) -> crate::Result<Signals> {
52 let mut mask = SigSet::empty();
53 for &s in signals {
54 mask.add(s);
55 }
56
57 // Mask the signals for this thread
58 mask.thread_block()?;
59 // Create the SignalFd
60 let sfd = SignalFd::with_flags(&mask, SfdFlags::SFD_NONBLOCK | SfdFlags::SFD_CLOEXEC)?;
61
62 Ok(Signals {
63 sfd: Generic::new(sfd, Interest::READ, Mode::Level),
64 mask,
65 })
66 }
67
68 /// Add a list of signals to the signals source
69 ///
70 /// If this function returns an error, the signal mask of the thread may
71 /// have still been changed.
72 pub fn add_signals(&mut self, signals: &[Signal]) -> crate::Result<()> {
73 for &s in signals {
74 self.mask.add(s);
75 }
76 self.mask.thread_block()?;
77 self.sfd.file.set_mask(&self.mask)?;
78 Ok(())
79 }
80
81 /// Remove a list of signals from the signals source
82 ///
83 /// If this function returns an error, the signal mask of the thread may
84 /// have still been changed.
85 pub fn remove_signals(&mut self, signals: &[Signal]) -> crate::Result<()> {
86 let mut removed = SigSet::empty();
87 for &s in signals {
88 self.mask.remove(s);
89 removed.add(s);
90 }
91 removed.thread_unblock()?;
92 self.sfd.file.set_mask(&self.mask)?;
93 Ok(())
94 }
95
96 /// Replace the list of signals of the source
97 ///
98 /// If this function returns an error, the signal mask of the thread may
99 /// have still been changed.
100 pub fn set_signals(&mut self, signals: &[Signal]) -> crate::Result<()> {
101 let mut new_mask = SigSet::empty();
102 for &s in signals {
103 new_mask.add(s);
104 }
105
106 self.mask.thread_unblock()?;
107 new_mask.thread_block()?;
108 self.sfd.file.set_mask(&new_mask)?;
109 self.mask = new_mask;
110
111 Ok(())
112 }
113 }
114
115 impl Drop for Signals {
116 fn drop(&mut self) {
117 // we cannot handle error here
118 if let Err(e) = self.mask.thread_unblock() {
119 log::warn!("[calloop] Failed to unmask signals: {:?}", e);
120 }
121 }
122 }
123
124 impl EventSource for Signals {
125 type Event = Event;
126 type Metadata = ();
127 type Ret = ();
128 type Error = SignalError;
129
130 fn process_events<C>(
131 &mut self,
132 readiness: Readiness,
133 token: Token,
134 mut callback: C,
135 ) -> Result<PostAction, Self::Error>
136 where
137 C: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
138 {
139 self.sfd
140 .process_events(readiness, token, |_, sfd| {
141 loop {
142 match sfd.read_signal() {
143 Ok(Some(info)) => callback(Event { info }, &mut ()),
144 Ok(None) => break,
145 Err(e) => {
146 log::warn!("[callop] Error reading from signalfd: {}", e);
147 return Err(e.into());
148 }
149 }
150 }
151 Ok(PostAction::Continue)
152 })
153 .map_err(|e| SignalError(e.into()))
154 }
155
156 fn register(&mut self, poll: &mut Poll, token_factory: &mut TokenFactory) -> crate::Result<()> {
157 self.sfd.register(poll, token_factory)
158 }
159
160 fn reregister(
161 &mut self,
162 poll: &mut Poll,
163 token_factory: &mut TokenFactory,
164 ) -> crate::Result<()> {
165 self.sfd.reregister(poll, token_factory)
166 }
167
168 fn unregister(&mut self, poll: &mut Poll) -> crate::Result<()> {
169 self.sfd.unregister(poll)
170 }
171 }
172
173 /// An error arising from processing events for a process signal.
174 #[derive(thiserror::Error, Debug)]
175 #[error(transparent)]
176 pub struct SignalError(Box<dyn std::error::Error + Sync + Send>);