1 //! Interface for the `signalfd` syscall.
2 //!
3 //! # Signal discarding
4 //! When a signal can't be delivered to a process (or thread), it will become a pending signal.
5 //! Failure to deliver could happen if the signal is blocked by every thread in the process or if
6 //! the signal handler is still handling a previous signal.
7 //!
8 //! If a signal is sent to a process (or thread) that already has a pending signal of the same
9 //! type, it will be discarded. This means that if signals of the same type are received faster than
10 //! they are processed, some of those signals will be dropped. Because of this limitation,
11 //! `signalfd` in itself cannot be used for reliable communication between processes or threads.
12 //!
13 //! Once the signal is unblocked, or the signal handler is finished, and a signal is still pending
14 //! (ie. not consumed from a signalfd) it will be delivered to the signal handler.
15 //!
16 //! Please note that signal discarding is not specific to `signalfd`, but also happens with regular
17 //! signal handlers.
18 use crate::unistd;
19 use crate::Result;
20 use crate::errno::Errno;
21 pub use crate::sys::signal::{self, SigSet};
22 pub use libc::signalfd_siginfo as siginfo;
23
24 use std::os::unix::io::{RawFd, AsRawFd};
25 use std::mem;
26
27
28 libc_bitflags!{
29 pub struct SfdFlags: libc::c_int {
30 SFD_NONBLOCK;
31 SFD_CLOEXEC;
32 }
33 }
34
35 pub const SIGNALFD_NEW: RawFd = -1;
36 #[deprecated(since = "0.23.0", note = "use mem::size_of::<siginfo>() instead")]
37 pub const SIGNALFD_SIGINFO_SIZE: usize = mem::size_of::<siginfo>();
38
39 /// Creates a new file descriptor for reading signals.
40 ///
41 /// **Important:** please read the module level documentation about signal discarding before using
42 /// this function!
43 ///
44 /// The `mask` parameter specifies the set of signals that can be accepted via this file descriptor.
45 ///
46 /// A signal must be blocked on every thread in a process, otherwise it won't be visible from
47 /// signalfd (the default handler will be invoked instead).
48 ///
49 /// See [the signalfd man page for more information](https://man7.org/linux/man-pages/man2/signalfd.2.html)
signalfd(fd: RawFd, mask: &SigSet, flags: SfdFlags) -> Result<RawFd>50 pub fn signalfd(fd: RawFd, mask: &SigSet, flags: SfdFlags) -> Result<RawFd> {
51 unsafe {
52 Errno::result(libc::signalfd(fd as libc::c_int, mask.as_ref(), flags.bits()))
53 }
54 }
55
56 /// A helper struct for creating, reading and closing a `signalfd` instance.
57 ///
58 /// **Important:** please read the module level documentation about signal discarding before using
59 /// this struct!
60 ///
61 /// # Examples
62 ///
63 /// ```
64 /// # use nix::sys::signalfd::*;
65 /// // Set the thread to block the SIGUSR1 signal, otherwise the default handler will be used
66 /// let mut mask = SigSet::empty();
67 /// mask.add(signal::SIGUSR1);
68 /// mask.thread_block().unwrap();
69 ///
70 /// // Signals are queued up on the file descriptor
71 /// let mut sfd = SignalFd::with_flags(&mask, SfdFlags::SFD_NONBLOCK).unwrap();
72 ///
73 /// match sfd.read_signal() {
74 /// // we caught a signal
75 /// Ok(Some(sig)) => (),
76 /// // there were no signals waiting (only happens when the SFD_NONBLOCK flag is set,
77 /// // otherwise the read_signal call blocks)
78 /// Ok(None) => (),
79 /// Err(err) => (), // some error happend
80 /// }
81 /// ```
82 #[derive(Debug, Eq, Hash, PartialEq)]
83 pub struct SignalFd(RawFd);
84
85 impl SignalFd {
new(mask: &SigSet) -> Result<SignalFd>86 pub fn new(mask: &SigSet) -> Result<SignalFd> {
87 Self::with_flags(mask, SfdFlags::empty())
88 }
89
with_flags(mask: &SigSet, flags: SfdFlags) -> Result<SignalFd>90 pub fn with_flags(mask: &SigSet, flags: SfdFlags) -> Result<SignalFd> {
91 let fd = signalfd(SIGNALFD_NEW, mask, flags)?;
92
93 Ok(SignalFd(fd))
94 }
95
set_mask(&mut self, mask: &SigSet) -> Result<()>96 pub fn set_mask(&mut self, mask: &SigSet) -> Result<()> {
97 signalfd(self.0, mask, SfdFlags::empty()).map(drop)
98 }
99
read_signal(&mut self) -> Result<Option<siginfo>>100 pub fn read_signal(&mut self) -> Result<Option<siginfo>> {
101 let mut buffer = mem::MaybeUninit::<siginfo>::uninit();
102
103 let size = mem::size_of_val(&buffer);
104 let res = Errno::result(unsafe {
105 libc::read(self.0, buffer.as_mut_ptr() as *mut libc::c_void, size)
106 }).map(|r| r as usize);
107 match res {
108 Ok(x) if x == size => Ok(Some(unsafe { buffer.assume_init() })),
109 Ok(_) => unreachable!("partial read on signalfd"),
110 Err(Errno::EAGAIN) => Ok(None),
111 Err(error) => Err(error)
112 }
113 }
114 }
115
116 impl Drop for SignalFd {
drop(&mut self)117 fn drop(&mut self) {
118 let e = unistd::close(self.0);
119 if !std::thread::panicking() && e == Err(Errno::EBADF) {
120 panic!("Closing an invalid file descriptor!");
121 };
122 }
123 }
124
125 impl AsRawFd for SignalFd {
as_raw_fd(&self) -> RawFd126 fn as_raw_fd(&self) -> RawFd {
127 self.0
128 }
129 }
130
131 impl Iterator for SignalFd {
132 type Item = siginfo;
133
next(&mut self) -> Option<Self::Item>134 fn next(&mut self) -> Option<Self::Item> {
135 match self.read_signal() {
136 Ok(Some(sig)) => Some(sig),
137 Ok(None) | Err(_) => None,
138 }
139 }
140 }
141
142
143 #[cfg(test)]
144 mod tests {
145 use super::*;
146
147 #[test]
create_signalfd()148 fn create_signalfd() {
149 let mask = SigSet::empty();
150 let fd = SignalFd::new(&mask);
151 assert!(fd.is_ok());
152 }
153
154 #[test]
create_signalfd_with_opts()155 fn create_signalfd_with_opts() {
156 let mask = SigSet::empty();
157 let fd = SignalFd::with_flags(&mask, SfdFlags::SFD_CLOEXEC | SfdFlags::SFD_NONBLOCK);
158 assert!(fd.is_ok());
159 }
160
161 #[test]
read_empty_signalfd()162 fn read_empty_signalfd() {
163 let mask = SigSet::empty();
164 let mut fd = SignalFd::with_flags(&mask, SfdFlags::SFD_NONBLOCK).unwrap();
165
166 let res = fd.read_signal();
167 assert!(res.unwrap().is_none());
168 }
169 }
170