interprocess_docfix/os/unix/
signal.rs

1//! Signal support for Unix-like systems.
2//!
3//! Signals in Unix are much more functional and versatile than ANSI C signals – there is simply much, much more of them. In addition to that, there is a special group of signals called "real-time signals" (more on those below).
4//!
5//! # Main signals
6//! The [`SignalType`] enumeration provides all standard signals as defined in POSIX.1-2001. More signal types may be added later, which is why exhaustively matching on it is not possible. It can be cheaply converted to a 32-bit integer, though. See its documentation for more on conversions.
7//!
8//! The `set_handler` function is used to create an association between a `SignalType` and a signal handling strategy.
9//!
10//! # Real-time signals
11//! In addition to usual signals, there's a special group of signals called "real-time signals". Those signals do not have fixed identifiers and are not generated by the system or kernel. Instead, they can only be sent between processes.
12//!
13//! # Signal-safe C functions
14//! Very few C functions can be called from a signal handler. Allocating memory, using the thread API and manipulating interval timers, for example, is prohibited in a signal handler. Calling a function which is not signal safe results in undefined behavior, i.e. memory unsafety. Rather than excluding certain specific functions, the POSIX specification only speicifies functions which *are* signal-safe. The following C functions are guaranteed to be safe to call from a signal handler:
15//! - `_Exit`
16//! - `_exit`
17//! - `abort`
18//! - `accept`
19//! - `access`
20//! - `aio_error`
21//! - `aio_return`
22//! - `aio_suspend`
23//! - `alarm`
24//! - `bind`
25//! - `cfgetispeed`
26//! - `cfgetospeed`
27//! - `cfsetispeed`
28//! - `cfsetospeed`
29//! - `chdir`
30//! - `chmod`
31//! - `chown`
32//! - `clock_gettime`
33//! - `close`
34//! - `connect`
35//! - `creat`
36//! - `dup`
37//! - `dup2`
38//! - `execle`
39//! - `execve`
40//! - `fchmod`
41//! - `fchown`
42//! - `fcntl`
43//! - `fdatasync`
44//! - `fork`
45//! - `fpathconf`
46//! - `fstat`
47//! - `fsync`
48//! - `ftruncate`
49//! - `getegid`
50//! - `geteuid`
51//! - `getgid`
52//! - `getgroups`
53//! - `getpeername`
54//! - `getpgrp`
55//! - `getpid`
56//! - `getppid`
57//! - `getsockname`
58//! - `getsockopt`
59//! - `getuid`
60//! - `kill`
61//! - `link`
62//! - `listen`
63//! - `lseek`
64//! - `lstat`
65//! - `mkdir`
66//! - `mkfifo`
67//! - `open`
68//! - `pathconf`
69//! - `pause`
70//! - `pipe`
71//! - `poll`
72//! - `posix_trace_event`
73//! - `pselect`
74//! - `raise`
75//! - `read`
76//! - `readlink`
77//! - `recv`
78//! - `recvfrom`
79//! - `recvmsg`
80//! - `rename`
81//! - `rmdir`
82//! - `select`
83//! - `sem_post`
84//! - `send`
85//! - `sendmsg`
86//! - `sendto`
87//! - `setgid`
88//! - `setpgid`
89//! - `setsid`
90//! - `setsockopt`
91//! - `setuid`
92//! - `shutdown`
93//! - `sigaction`
94//! - `sigaddset`
95//! - `sigdelset`
96//! - `sigemptyset`
97//! - `sigfillset`
98//! - `sigismember`
99//! - `signal`
100//! - `sigpause`
101//! - `sigpending`
102//! - `sigprocmask`
103//! - `sigqueue`
104//! - `sigset`
105//! - `sigsuspend`
106//! - `sleep`
107//! - `sockatmark`
108//! - `socket`
109//! - `socketpair`
110//! - `stat`
111//! - `symlink`
112//! - `sysconf`
113//! - `tcdrain`
114//! - `tcflow`
115//! - `tcflush`
116//! - `tcgetattr`
117//! - `tcgetpgrp`
118//! - `tcsendbreak`
119//! - `tcsetattr`
120//! - `tcsetpgrp`
121//! - `time`
122//! - `timer_getoverrun`
123//! - `timer_gettime`
124//! - `timer_settime`
125//! - `times`
126//! - `umask`
127//! - `uname`
128//! - `unlink`
129//! - `utime`
130//! - `wait`
131//! - `waitpid`
132//! - `write`
133//!
134//! Many Rust crates, including the standard library, use signal-unsafe functions not on this list in safe code. For example, `Vec`, `Box` and `Rc`/`Arc` perform memory allocations, and `Mutex`/`RwLock` perform `pthread` calls. For this reason, creating a signal hook is an unsafe operation.
135//!
136//! [`SignalType`]: enum.SignalType.html " "
137
138use super::imports::*;
139use cfg_if::cfg_if;
140use std::{
141    convert::{TryFrom, TryInto},
142    error::Error,
143    fmt::{self, Display, Formatter},
144    io,
145    mem::zeroed,
146    panic, process,
147};
148use to_method::To;
149
150cfg_if! {
151    if #[cfg(any(
152        target_os = "linux",
153        target_os = "android",
154    ))] {
155        // don't care about LinuxThreads lmao
156        const SIGRTMIN: i32 = 34;
157        const SIGRTMAX: i32 = 64;
158    } else if #[cfg(target_os = "freebsd")] {
159        const SIGRTMIN: i32 = 65;
160        const SIGRTMAX: i32 = 126;
161    } else if #[cfg(target_os = "netbsd")] {
162        const SIGRTMIN: i32 = 33;
163        const SIGRTMAX: i32 = 63;
164    } else if #[cfg(target_os = "redox")] {
165        const SIGRTMIN: i32 = 27;
166        const SIGRTMAX: i32 = 31;
167    } else {
168        const SIGRTMIN: i32 = 1; // min is smaller than max so that the sloppy calculation works
169        const SIGRTMAX: i32 = 0;
170    }
171}
172
173/// Whether real-time signals are supported at all.
174///
175/// The platforms for which `interprocess` has explicit support for real-time signals are:
176/// - Linux
177///     - includes Android
178/// - FreeBSD
179/// - NetBSD
180/// - Redox
181pub const REALTIME_SIGNALS_SUPPORTED: bool = NUM_REALTIME_SIGNALS != 0;
182/// How many real-time signals are supported. Remember that real-time signals start from 0, so this number is higher than the highest possible real-time signal by 1.
183///
184/// Platform-specific values for this constant are:
185/// - **Linux** and **NetBSD**: 31
186/// - **FreeBSD**: 62
187/// - **Redox**: 5 (does not conform with POSIX)
188pub const NUM_REALTIME_SIGNALS: u32 = (SIGRTMAX - SIGRTMIN + 1) as u32;
189/// Returns `true` if the specified signal is a valid real-time signal value, `false` otherwise.
190#[allow(clippy::absurd_extreme_comparisons)] // For systems where there are no realtime signals
191pub const fn is_valid_rtsignal(rtsignal: u32) -> bool {
192    rtsignal < NUM_REALTIME_SIGNALS
193}
194
195/// The first field is the current method of handling a specific signal, the second one is the flags which were set for it.
196#[cfg(all(unix, feature = "signals"))]
197type HandlerAndFlags = (SignalHandler, i32);
198
199#[cfg(all(unix, feature = "signals"))]
200static HANDLERS: Lazy<RwLock<IntMap<HandlerAndFlags>>> = Lazy::new(|| RwLock::new(IntMap::new()));
201
202/// Installs the specified handler for the specified standard signal, using the default values for the flags.
203///
204/// See [`HandlerOptions`] builder if you'd like to customize the flags.
205///
206/// # Example
207/// ```no_run
208/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
209/// # #[cfg(all(unix, feature = "signals"))] {
210/// use interprocess::os::unix::signal::{self, SignalType, SignalHandler};
211///
212/// let handler = unsafe {
213///     // Since signal handlers are restricted to a specific set of C functions, creating a
214///     // handler from an arbitrary function is unsafe because it might call a function
215///     // outside the list, and there's no real way to know that at compile time with the
216///     // current version of Rust. Since we're only using the write() system call here, this
217///     // is safe.
218///     SignalHandler::from_fn(|| {
219///         println!("You pressed Ctrl-C!");
220///     })
221/// };
222///
223/// // Install our handler for the KeyboardInterrupt signal type.
224/// signal::set_handler(SignalType::KeyboardInterrupt, handler)?;
225/// # }
226/// # Ok(()) }
227/// ```
228///
229/// [`HandlerOptions`]: struct.HandlerOptions.html " "
230pub fn set_handler(signal_type: SignalType, handler: SignalHandler) -> Result<(), SetHandlerError> {
231    HandlerOptions::for_signal(signal_type)
232        .set_new_handler(handler)
233        .set()
234}
235/// Installs the specified handler for the specified unsafe signal, using the default values for the flags.
236///
237/// See [`HandlerOptions`] builder if you'd like to customize the flags.
238///
239/// # Safety
240/// See the [`set_unsafe`] safety notes.
241///
242/// # Example
243/// ```no_run
244/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
245/// # #[cfg(all(unix, feature = "signals"))] {
246/// use interprocess::os::unix::signal::{self, SignalType, SignalHandler};
247///
248/// let handler = unsafe {
249///     // Since signal handlers are restricted to a specific set of C functions, creating a
250///     // handler from an arbitrary function is unsafe because it might call a function
251///     // outside the list, and there's no real way to know that at compile time with the
252///     // current version of Rust. Since we're only using the write() system call here, this
253///     // is safe.
254///     SignalHandler::from_fn(|| {
255///         println!("Oh no, the motherboard broke!");
256///         std::process::abort();
257///     })
258/// };
259///
260/// unsafe {
261///     // Install our handler for the MemoryBusError signal type.
262///     signal::set_unsafe_handler(SignalType::MemoryBusError, handler)?;
263/// }
264/// # }
265/// # Ok(()) }
266/// ```
267///
268/// [`HandlerOptions`]: struct.HandlerOptions.html " "
269/// [`set_unsafe`]: struct.HandlerOptions.html#method.set_unsafe " "
270pub unsafe fn set_unsafe_handler(
271    signal_type: SignalType,
272    handler: SignalHandler,
273) -> Result<(), SetHandlerError> {
274    unsafe {
275        HandlerOptions::for_signal(signal_type)
276            .set_new_handler(handler)
277            .set_unsafe()
278    }
279}
280/// Installs the specified handler for the specified real-time signal, using the default values for the flags.
281///
282/// See [`HandlerOptions`] builder if you'd like to customize the flags.
283///
284/// # Example
285/// ```no_run
286/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
287/// # #[cfg(all(unix, feature = "signals"))] {
288/// use interprocess::os::unix::signal::{self, SignalHandler};
289///
290/// let handler = unsafe {
291///     // Since signal handlers are restricted to a specific set of C functions, creating a
292///     // handler from an arbitrary function is unsafe because it might call a function
293///     // outside the list, and there's no real way to know that at compile time with the
294///     // current version of Rust. Since we're only using the write() system call here, this
295///     // is safe.
296///     SignalHandler::from_fn(|| {
297///         println!("You sent a real-time signal!");
298///     })
299/// };
300///
301/// // Install our handler for the real-time signal 0.
302/// signal::set_rthandler(0, handler)?;
303/// # }
304/// # Ok(()) }
305/// ```
306///
307/// [`HandlerOptions`]: struct.HandlerOptions.html " "
308pub fn set_rthandler(rtsignal: u32, handler: SignalHandler) -> Result<(), SetHandlerError> {
309    HandlerOptions::for_rtsignal(rtsignal)
310        .set_new_handler(handler)
311        .set()
312}
313
314unsafe fn install_hook(signum: i32, hook: usize, flags: i32) -> io::Result<()> {
315    let success = {
316        let [mut old_handler, mut new_handler] = unsafe {
317            // SAFETY: sigaction only consists of integers and therefore can
318            // contain an all-0 bit pattern
319            [zeroed::<sigaction>(); 2]
320        };
321        new_handler.sa_sigaction = hook;
322        new_handler.sa_flags = flags;
323        unsafe {
324            // SAFETY: all the pointers that are being passed come from references and only involve
325            // a single cast, which means that it's just a reference-to-pointer cast and not a
326            // pointer-to-pointer cast (the latter can cast any pointer to any other pointer, but
327            // you need two casts in order to convert a reference to a pointer to an arbitrary type)
328            libc::sigaction(signum, &new_handler as *const _, &mut old_handler as *mut _) != -1
329        }
330    };
331    if success {
332        Ok(())
333    } else {
334        Err(io::Error::last_os_error())
335    }
336}
337
338/// Options for installing a signal handler.
339///
340/// # Example
341/// ```no_run
342/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
343/// # #[cfg(all(unix, feature = "signals"))] {
344/// use interprocess::os::unix::signal::{self, SignalType, SignalHandler};
345///
346/// let handler = unsafe {
347///     // Since signal handlers are restricted to a specific set of C functions, creating a
348///     // handler from an arbitrary function is unsafe because it might call a function
349///     // outside the list, and there's no real way to know that at compile time with the
350///     // current version of Rust. Since we're only using the write() system call here, this
351///     // is safe.
352///     SignalHandler::from_fn(|| {
353///         println!("You pressed Ctrl-C!");
354///     })
355/// };
356///
357/// // Let's use the builder to customize the signal handler:
358/// signal::HandlerOptions::for_signal(SignalType::KeyboardInterrupt)
359///     .set_new_handler(handler)
360///     .auto_reset_handler(true) // Let's remove the signal handler after it fires once.
361///     .system_call_restart(false) // Avoid restarting system calls and let them fail with the
362///                                 // Interrupted error type. There normally isn't a reason to
363///                                 // do this, but for the sake of the example, let's assume
364///                                 // that there is.
365///     .set()?; // Finalize the builder by installing the handler.
366/// # }
367/// # Ok(()) }
368/// ```
369#[derive(Copy, Clone, Debug, PartialEq, Eq)]
370#[must_use = "the signal handler is attached by calling `.set()`, which consumes the builder"]
371pub struct HandlerOptions {
372    signal: i32,
373    /// The handler to be set up. If `None`, the handler is not changed by the call.
374    pub handler: Option<SignalHandler>,
375    /// For the [`ChildProcessEvent`] signal, this option *disables* receiving the signal if it was generated because the child process was suspended (using any signal which suspends a process, such as [`Suspend`] or [`ForceSuspend`]) or [resumed][`Continue`].
376    ///
377    /// If enabled on a signal which is not [`ChildProcessEvent`], a panic is produced in debug builds when [`set`] is called; in release builds, the flag is simply ignored.
378    ///
379    /// [`ChildProcessEvent`]: enum.SignalType.html#variant.ChildProcessEvent " "
380    /// [`Suspend`]: enum.SignalType.html#variant.Suspend " "
381    /// [`ForceSuspend`]: enum.SignalType.html#variant.ForceSuspend " "
382    /// [`Continue`]: enum.SignalType.html#variant.Continue " "
383    /// [`set`]: #method.set " "
384    pub ignore_child_stop_events: bool,
385    /// Allow the signal handler to interrupt a previous invocation of itself. If disabled, the signal handler will disable its own signal when called and restore previous state when it finishes executing. If not, an infinite amount of signals can be received on top of each other, which is likely a stack overflow risk.
386    ///
387    /// If enabled but the handler is [set to use the default handling method][`Default`] from the OS, a panic is produced in debug builds when [`set`] is called; in release builds, the flag is simply ignored.
388    ///
389    /// [`Default`]: enum.SignalHandler.html#variant.Default " "
390    /// [`set`]: #method.set " "
391    pub recursive_handler: bool,
392    /// Automatically restart certain system calls instead of failing with the [`Interrupted`] error type. Some other system calls are not restarted with this function and may fail with [`Interrupted`] anyway. Consult your manual pages for more details.
393    ///
394    /// [`Interrupted`]: https://doc.rust-lang.org/std/io/enum.ErrorKind.html#variant.Interrupted " "
395    pub system_call_restart: bool,
396    /// Automatically reset the handler to the default handling method whenever it is executed.
397    ///
398    /// If enabled but the handler is [set to use the default handling method][`Default`] from the OS, a panic is produced in debug builds when [`set`] is called; in release builds, the flag is simply ignored.
399    ///
400    /// [`Default`]: enum.SignalHandler.html#variant.Default " "
401    /// [`set`]: #method.set " "
402    pub auto_reset_handler: bool,
403}
404impl HandlerOptions {
405    /// Creates a builder for a handler for the specified signal.
406    pub fn for_signal(signal: SignalType) -> Self {
407        Self {
408            signal: signal.into(),
409            handler: None,
410            ignore_child_stop_events: false,
411            recursive_handler: false,
412            system_call_restart: true,
413            auto_reset_handler: false,
414        }
415    }
416    /// Creates a builder for a handler for the specified real-time signal.
417    ///
418    /// # Panics
419    /// Guaranteed to panic if the specified real-time signal is outside the range of real-time signals supported by the OS. See [`NUM_REALTIME_SIGNALS`].
420    ///
421    /// [`NUM_REALTIME_SIGNALS`]: constant.NUM_REALTIME_SIGNALS.html " "
422    pub fn for_rtsignal(rtsignal: u32) -> Self {
423        assert!(
424            is_valid_rtsignal(rtsignal),
425            "invalid real-time signal value – check the NUM_REALTIME_SIGNALS constant to see how \
426            many are supported"
427        );
428        Self {
429            signal: rtsignal as i32,
430            handler: None,
431            ignore_child_stop_events: false,
432            recursive_handler: false,
433            system_call_restart: true,
434            auto_reset_handler: false,
435        }
436    }
437    /// Sets the handler for the signal to the specified value. If `None`, the old value is used.
438    pub fn set_new_handler(mut self, handler: impl Into<Option<SignalHandler>>) -> Self {
439        self.handler = handler.into();
440        self
441    }
442    /// Sets the [`ignore_child_stop_events`] flag to the specified value.
443    ///
444    /// [`ignore_child_stop_events`]: #structfield.ignore_child_stop_events " "
445    pub fn ignore_child_stop_events(mut self, ignore: impl Into<bool>) -> Self {
446        self.ignore_child_stop_events = ignore.into();
447        self
448    }
449    /// Sets the [`recursive_handler`] flag to the specified value.
450    ///
451    /// [`recursive_handler`]: #structfield.recursive_handler " "
452    pub fn recursive_handler(mut self, recursive: impl Into<bool>) -> Self {
453        self.recursive_handler = recursive.into();
454        self
455    }
456    /// Sets the [`system_call_restart`] flag to the specified value.
457    ///
458    /// [`system_call_restart`]: #structfield.system_call_restart " "
459    pub fn system_call_restart(mut self, restart: impl Into<bool>) -> Self {
460        self.system_call_restart = restart.into();
461        self
462    }
463    /// Sets the [`auto_reset_handler`] flag to the specified value.
464    ///
465    /// [`auto_reset_handler`]: #structfield.auto_reset_handler " "
466    pub fn auto_reset_handler(mut self, reset: impl Into<bool>) -> Self {
467        self.auto_reset_handler = reset.into();
468        self
469    }
470    /// Installs the signal handler.
471    pub fn set(self) -> Result<(), SetHandlerError> {
472        if let Ok(val) = SignalType::try_from(self.signal) {
473            if val.is_unsafe() {
474                return Err(SetHandlerError::UnsafeSignal);
475            }
476        }
477        unsafe { self.set_unsafe() }
478    }
479
480    /// Installs the signal handler, even if the signal being handled is unsafe.
481    ///
482    /// # Safety
483    /// The handler and all code that may or may not execute afterwards must be prepared for the aftermath of what might've caused the signal.
484    ///
485    /// [`SegmentationFault`] or [`BusError`] are most likely caused by undefined behavior invoked from Rust (the former is caused by dereferencing invalid memory, the latter is caused by dereferencing an incorrectly aligned pointer on ISAs like ARM which do not tolerate misaligned pointers), which means that the program is unsound and the only meaningful thing to do is to capture as much information as possible in a safe way – preferably using OS services to create a dump, rather than trying to read the program's global state, which might be irreversibly corrupted – and write the crash dump to some on-disk location.
486    ///
487    /// [`SegmentationFault`]: enum.SignalType.html#variant.SegmentationFault " "
488    /// [`BusError`]: enum.SignalType.html#variant.BusError " "
489    pub unsafe fn set_unsafe(self) -> Result<(), SetHandlerError> {
490        if let Ok(val) = SignalType::try_from(self.signal) {
491            if val.is_unblockable() {
492                return Err(SetHandlerError::UnblockableSignal(val));
493            }
494        } else if !is_valid_rtsignal(self.signal as u32) {
495            return Err(SetHandlerError::RealTimeSignalOutOfBounds {
496                attempted: self.signal as u32,
497                max: NUM_REALTIME_SIGNALS,
498            });
499        }
500        let handlers = HANDLERS.read();
501        let new_flags = self.flags_as_i32();
502        let mut need_to_upgrade_handle = false;
503        let need_to_install_hook =
504            if let Some((existing_handler, existing_flags)) = handlers.get(self.signal as u64) {
505                // This signal's handler was set before – check if we need to install new flags or if
506                // one is default and another isn't, which would mean that either that no hook was
507                // installed and we have to install one or there was one installed but we need to
508                // install the default hook explicitly.
509                let new_handler = self.handler.unwrap_or_default();
510                if new_handler != *existing_handler || new_flags != *existing_flags {
511                    need_to_upgrade_handle = true;
512                    true
513                } else {
514                    let one_handler_is_default_and_another_isnt = (new_handler.is_default()
515                        && !existing_handler.is_default())
516                        || (!new_handler.is_default() && existing_handler.is_default());
517                    *existing_flags != new_flags || one_handler_is_default_and_another_isnt
518                }
519            } else {
520                need_to_upgrade_handle = true;
521                !self.handler.unwrap_or_default().is_default()
522            };
523        drop(handlers);
524        if need_to_upgrade_handle {
525            let mut handlers = HANDLERS.write();
526            let signal_u64 = self.signal as u64;
527            handlers.remove(signal_u64);
528            handlers.insert(signal_u64, (self.handler.unwrap_or_default(), new_flags));
529        }
530        if need_to_install_hook {
531            let hook_val = match self.handler.unwrap_or_default() {
532                SignalHandler::Default => SIG_DFL,
533                _ => signal_receiver as usize,
534            };
535            unsafe {
536                // SAFETY: we're using a correct value for the hook
537                install_hook(self.signal, hook_val, new_flags)?
538            }
539        }
540        Ok(())
541    }
542
543    fn flags_as_i32(self) -> i32 {
544        if self.handler.unwrap_or_default().is_default() {
545            debug_assert!(
546                !self.recursive_handler,
547                "cannot use the recursive_handler flag with the default handling method",
548            );
549        }
550        if self.signal != SIGCHLD {
551            debug_assert!(
552                !self.ignore_child_stop_events,
553                "\
554cannot use the ignore_child_stop_events flag when the signal to be handled isn't \
555ChildProcessEvent",
556            );
557        }
558        let mut flags = 0;
559        if self.auto_reset_handler {
560            flags |= SA_RESETHAND;
561        }
562        if self.ignore_child_stop_events {
563            flags |= SA_NOCLDSTOP;
564        }
565        if self.recursive_handler {
566            flags |= SA_NODEFER;
567        }
568        if self.system_call_restart {
569            flags |= SA_RESTART;
570        }
571        flags
572    }
573}
574
575/// The error produced when setting a signal handler fails.
576#[derive(Debug)]
577#[cfg_attr(all(unix, feature = "signals"), derive(Error))]
578pub enum SetHandlerError {
579    /// An unsafe signal was attempted to be handled using `set` instead of `set_unsafe`.
580    #[cfg_attr(
581        all(unix, feature = "signals"),
582        error("an unsafe signal was attempted to be handled using `set` instead of `set_unsafe`")
583    )]
584    UnsafeSignal,
585    /// The signal which was attempted to be handled is not allowed to be handled by the POSIX specification. This can either be [`ForceSuspend`] or [`Kill`].
586    ///
587    /// [`Kill`]: enum.SignalType.html#variant.Kill " "
588    /// [`ForceSuspend`]: enum.SignalType.html#variant.ForceSuspend " "
589    #[cfg_attr(
590        all(unix, feature = "signals"),
591        error("the signal {:?} cannot be handled", .0),
592    )]
593    UnblockableSignal(SignalType),
594    /// The specified real-time signal is not available on this OS.
595    #[cfg_attr(
596        all(unix, feature = "signals"),
597        error(
598            "the real-time signal number {} is not available ({} is the highest possible)",
599            .attempted,
600            .max,
601        ),
602    )]
603    RealTimeSignalOutOfBounds {
604        /// The realtime signal which was attempted to be used.
605        attempted: u32,
606        /// The highest available realtime signal number.
607        max: u32,
608    },
609    /// An unexpected OS error ocurred during signal handler setup.
610    #[cfg_attr(
611        all(unix, feature = "signals"),
612        error("{}", .0),
613    )]
614    UnexpectedSystemCallFailure(#[cfg_attr(all(unix, feature = "signals"), from)] io::Error),
615}
616
617/// The actual hook which is passed to `sigaction` which dispatches signals according to the global handler map (the `HANDLERS` static).
618extern "C" fn signal_receiver(signum: i32) {
619    let catched = panic::catch_unwind(|| {
620        let handler_and_flags = {
621            let handlers = HANDLERS.read();
622            let val = handlers
623                .get(signum as u64)
624                .expect("unregistered signal passed by the OS to the shared receiver");
625            *val
626        };
627        match handler_and_flags.0 {
628            SignalHandler::Ignore => {}
629            SignalHandler::Hook(hook) => hook.inner()(),
630            SignalHandler::Default => unreachable!(
631                "signal receiver was unregistered but has been called by the OS anyway"
632            ),
633        }
634        if handler_and_flags.1 & SA_RESETHAND != 0 {
635            // If the signal is set to be reset to default handling, set the record accordingly.
636            let mut handlers = HANDLERS.write();
637            handlers.remove(signum as u64);
638            let handler_and_flags = (SignalHandler::Default, handler_and_flags.1);
639            handlers.insert(signum as u64, handler_and_flags);
640        }
641    });
642    // The panic hook already ran, so we only have to abort the process
643    catched.unwrap_or_else(|_| process::abort());
644}
645
646/// A signal handling method.
647#[derive(Copy, Clone, Debug, PartialEq, Eq)]
648pub enum SignalHandler {
649    /// Use the default behavior specified by POSIX.
650    Default,
651    /// Ignore the signal whenever it is received.
652    Ignore,
653    /// Call a function whenever the signal is received.
654    Hook(SignalHook),
655}
656impl SignalHandler {
657    /// Returns `true` for the [`Default`] variant, `false` otherwise.
658    ///
659    /// [`Default`]: #variant.Default.html " "
660    pub const fn is_default(self) -> bool {
661        matches!(self, Self::Default)
662    }
663    /// Returns `true` for the [`Ignore`] variant, `false` otherwise.
664    ///
665    /// [`Ignore`]: #variant.Ignore.html " "
666    pub const fn is_ignore(self) -> bool {
667        matches!(self, Self::Ignore)
668    }
669    /// Returns `true` for the [`Hook`] variant, `false` otherwise.
670    ///
671    /// [`Hook`]: #variant.Hook.html " "
672    pub const fn is_hook(self) -> bool {
673        matches!(self, Self::Hook(..))
674    }
675    /// Creates a handler which calls the specified function.
676    ///
677    /// # Safety
678    /// The function must not call any C functions which are not considered signal-safe. See the [module-level section on signal-safe C functions] for more.
679    ///
680    /// [module-level section on signal-safe C functions]: index.html#signal-safe-c-functions " "
681    pub unsafe fn from_fn(function: fn()) -> Self {
682        Self::Hook(unsafe { SignalHook::from_fn(function) })
683    }
684}
685impl Default for SignalHandler {
686    /// Returns [`SignalHandler::Default`].
687    ///
688    /// [`SignalHandler::Default`]: #variant.Default " "
689    fn default() -> Self {
690        Self::Default
691    }
692}
693impl From<SignalHook> for SignalHandler {
694    fn from(op: SignalHook) -> Self {
695        Self::Hook(op)
696    }
697}
698/// A function which can be used as a signal handler.
699#[repr(transparent)]
700#[derive(Copy, Clone, Debug, PartialEq, Eq)]
701pub struct SignalHook(fn());
702impl SignalHook {
703    /// Creates a hook which calls the specified function.
704    ///
705    /// # Safety
706    /// The function must not call any C functions which are not considered signal-safe. See the [module-level section on signal-safe C functions] for more.
707    ///
708    /// [module-level section on signal-safe C functions]: index.html#signal-safe-c-functions " "
709    pub unsafe fn from_fn(function: fn()) -> Self {
710        Self(function)
711    }
712    /// Returns the wrapped function.
713    pub fn inner(self) -> fn() {
714        self.0
715    }
716}
717impl From<SignalHook> for fn() {
718    fn from(op: SignalHook) -> Self {
719        op.0
720    }
721}
722
723/// Sends the specified signal to the specified process. If the specified signal is `None`, no signal is sent and only a privilege check is performed instead.
724///
725/// # Example
726/// ```no_run
727/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
728/// # #[cfg(all(unix, feature = "signals"))] {
729/// use interprocess::os::unix::signal::{self, SignalType};
730/// use std::process;
731///
732/// // Send a Termination signal to the calling process.
733/// signal::send(SignalType::Termination, process::id())?;
734/// # }
735/// # Ok(()) }
736/// ```
737pub fn send(signal: impl Into<Option<SignalType>>, pid: impl Into<u32>) -> io::Result<()> {
738    let pid = pid
739        .to::<u32>()
740        .try_to::<i32>()
741        .unwrap_or_else(|_| panic!("process identifier out of range"));
742    debug_assert_ne!(
743        pid, 0,
744        "to send the signal to the process group of the calling process, use send_to_group instead"
745    );
746    let success = unsafe { libc::kill(signal.into().map_or(0, Into::into), pid) != -1 };
747    if success {
748        Ok(())
749    } else {
750        Err(io::Error::last_os_error())
751    }
752}
753/// Sends the specified real-time signal to the specified process. If the specified signal is `None`, no signal is sent and only a privilege check is performed instead.
754///
755/// # Example
756/// ```no_run
757/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
758/// # #[cfg(all(unix, feature = "signals"))] {
759/// use interprocess::os::unix::signal::{self, SignalType};
760/// use std::process;
761///
762/// // Send a real-timne signal 0 to the calling process.
763/// signal::send_rt(0, process::id())?;
764/// # }
765/// # Ok(()) }
766/// ```
767pub fn send_rt(signal: impl Into<Option<u32>>, pid: impl Into<u32>) -> io::Result<()> {
768    let pid = pid
769        .to::<u32>()
770        .try_to::<i32>()
771        .unwrap_or_else(|_| panic!("process identifier out of range"));
772    debug_assert_ne!(
773        pid, 0,
774        "to send the signal to the process group of the calling process, use send_to_group instead"
775    );
776    let signal = signal.into().map_or(0, |val| {
777        assert!(is_valid_rtsignal(val), "invalid real-time signal");
778        val
779    }) as i32;
780    let success = unsafe { libc::kill(signal, pid) != -1 };
781    if success {
782        Ok(())
783    } else {
784        Err(io::Error::last_os_error())
785    }
786}
787/// Sends the specified signal to the specified process group. If the specified signal is `None`, no signal is sent and only a privilege check is performed instead.
788///
789/// # Example
790/// ```no_run
791/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
792/// # #[cfg(all(unix, feature = "signals"))] {
793/// use interprocess::os::unix::signal::{self, SignalType};
794/// use std::process;
795///
796/// // Send a Termination signal to the process group of the calling process.
797/// signal::send_to_group(SignalType::Termination, 0_u32)?;
798/// # }
799/// # Ok(()) }
800/// ```
801pub fn send_to_group(signal: impl Into<Option<SignalType>>, pid: impl Into<u32>) -> io::Result<()> {
802    #[allow(clippy::neg_multiply)] // "it's more readable to just negate"? how about no
803    let pid = pid
804        .to::<u32>()
805        .try_to::<i32>()
806        .unwrap_or_else(|_| panic!("process group identifier out of range"))
807        * -1;
808    let success = unsafe { libc::kill(signal.into().map_or(0, Into::into), pid) != -1 };
809    if success {
810        Ok(())
811    } else {
812        Err(io::Error::last_os_error())
813    }
814}
815/// Sends the specified real-time signal to the specified process. If the specified signal is `None`, no signal is sent and only a privilege check is performed instead.
816///
817/// # Example
818/// ```no_run
819/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
820/// # #[cfg(all(unix, feature = "signals"))] {
821/// use interprocess::os::unix::signal::{self, SignalType};
822/// use std::process;
823///
824/// // Send a real-timne signal 0 to the process group of the calling process.
825/// signal::send_rt(0_u32, 0_u32)?;
826/// # }
827/// # Ok(()) }
828/// ```
829pub fn send_rt_to_group(signal: impl Into<Option<u32>>, pid: impl Into<u32>) -> io::Result<()> {
830    #[allow(clippy::neg_multiply)]
831    let pid = pid
832        .to::<u32>()
833        .try_to::<i32>()
834        .unwrap_or_else(|_| panic!("process identifier out of range"))
835        * -1;
836    debug_assert_ne!(
837        pid, 0,
838        "to send the signal to the process group of the calling process, use send_to_group instead"
839    );
840    let signal = signal.into().map_or(0, |val| {
841        assert!(is_valid_rtsignal(val), "invalid real-time signal");
842        val
843    }) as i32;
844    let success = unsafe { libc::kill(signal, pid) != -1 };
845    if success {
846        Ok(())
847    } else {
848        Err(io::Error::last_os_error())
849    }
850}
851
852/// All standard signal types as defined in POSIX.1-2001.
853///
854/// The values can be safely and quickly converted to [`i32`]/[`u32`]. The reverse process involves safety checks, making sure that unknown signal values are never stored.
855///
856/// [`i32`]: https://doc.rust-lang.org/std/primitive.i32.html " "
857/// [`u32`]: https://doc.rust-lang.org/std/primitive.u32.html " "
858#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
859#[repr(i32)]
860#[non_exhaustive]
861pub enum SignalType {
862    /// `SIGHUP` – lost connection to controlling terminal. Opting out of this signal is recommended if the process does not need to stop after the user who started it logs out.
863    ///
864    /// *Default handler: process termination.*
865    #[cfg(any(doc, se_basic))]
866    Hangup = SIGHUP,
867    /// `SIGINT` – keyboard interrupt, usually sent by pressing `Ctrl`+`C` by the terminal. This signal is typically set to be ignored if the program runs an interactive interface: GUI/TUI, interactive shell (the Python shell, for example) or any other kind of interface which runs in a loop, as opposed to a command-line invocation of the program which reads its standard input or command-line arguments, performs a task and exits. If the interactive interface is running a lengthy operation, a good idea is to temporarily re-enable the signal and abort the lengthy operation if the signal is received, then disable it again.
868    ///
869    /// *Default handler: process termination.*
870    #[cfg(any(doc, se_basic))]
871    KeyboardInterrupt = SIGINT,
872    /// `SIGQUIT` – request to perform a core dump and quit, usually sent by pressing `Ctrl`+`\`. This signal normally should not be overriden or masked out – the core dump is performed automatically by the OS.
873    ///
874    /// *Default handler: process termination with a core dump.*
875    #[cfg(any(doc, se_basic))]
876    QuitAndDump = SIGQUIT,
877    /// `SIGILL` – illegal or malformed instruction exception, generated by the CPU whenever such an instruction is executed. This signal normally should not be overriden or masked out, since it likely means that the executable file or the memory of the process has been corrupted and further execution is a risk of invoking negative consequences.
878    ///
879    /// For reasons described above, **this signal is considered unsafe** – handling it requires using `set_unsafe_handler`.
880    ///
881    /// *Default handler: process termination with a core dump.*
882    #[cfg(any(doc, se_basic))]
883    IllegalInstruction = SIGILL,
884    /// `SIGABRT` – abnormal termination requested. This signal is typically invoked by the program itself, using [`std::process::abort`] or the equivalent C function; still, like any other signal, it can be sent from outside the process.
885    ///
886    /// *Default handler: process termination with a core dump.*
887    ///
888    /// [`std::process::abort`]: https://doc.rust-lang.org/std/process/fn.abort.html " "
889    #[cfg(any(doc, se_basic))]
890    Abort = SIGABRT,
891    /// `SIGFPE` – mathematical exception. This signal is generated whenever an undefined mathematical operation is performed – mainly integer division by zero.
892    ///
893    /// *Default handler: process termination with a core dump.*
894    #[cfg(any(doc, se_basic))]
895    MathException = SIGFPE,
896    /// `SIGKILL` – forced termination. This signal can only be sent using the usual signal sending procedures and, unlike most other signals, cannot be masked out or handled at all. The main purpose for this signal is to stop a program which has masked out all other signals for malicious purposes or has stuck in such a state because of a bug.
897    ///
898    /// *Default handler: process termination, **cannot be overriden or disabled**.*
899    #[cfg(any(doc, se_basic))]
900    Kill = SIGKILL,
901    /// `SIGSEGV` – invaid memory access. This signal is issued by the OS whenever the program tries to access an invalid memory location, such as the `NULL` pointer or simply an address outside the user-mode address space as established by the OS. The only case when this signal can be received by a Rust program is if memory unsafety occurs due to misuse of unsafe code. As such, it should normally not be masked out or handled, as it likely indicates a critical bug (soundness hole), executable file corruption or process memory corruption.
902    ///
903    /// For reasons described above, **this signal is considered unsafe** – handling it requires using `set_unsafe_handler`.
904    ///
905    /// *Default handler: process termination with a core dump.*
906    #[cfg(any(doc, se_basic))]
907    SegmentationFault = SIGSEGV,
908    /// `SIGPIPE` – invalid access to an [unnamed pipe]. This signal is issued by the OS whenever a program attempts to write to an unnamed pipe which has no readers connected to it. If unexpected, this might mean abnormal termination of the process which the pipe was used to communicate with.
909    ///
910    /// *Default handler: process termination.*
911    ///
912    /// [unnamed pipe]: ../../../unnamed_pipe/index.html " "
913    #[cfg(any(doc, se_basic))]
914    BrokenPipe = SIGPIPE,
915    /// `SIGALRM` – "alarm clock" signal. This signal is issued by the OS when the arranged amount of real (wall clock) time expires. This clock can be set using the [`alarm`] and [`setitimer`] system calls.
916    ///
917    /// *Default handler: process termination.*
918    ///
919    /// [`alarm`]: https://www.man7.org/linux/man-pages/man2/alarm.2.html " "
920    /// [`setitimer`]: https://www.man7.org/linux/man-pages/man2/setitimer.2.html " "
921    #[cfg(any(doc, se_basic))]
922    AlarmClock = SIGALRM,
923    /// `SIGTERM` – request for termination. This signal can only be sent using the usual signal sending procedures. Unlike [`KeyboardInterrupt`], this signal is not a request to break out of a lengthy operation, but rather to close the program as a whole. Signal handlers for this signal are expected to perform minimal cleanup and quick state save procedures and then exit.
924    ///
925    /// *Default handler: process termination.*
926    ///
927    /// [`KeyboardInterrupt`]: #variant.KeyboardInterrupt " "
928    #[cfg(any(doc, se_basic))]
929    Termination = SIGTERM,
930    /// `SIGUSR1` – user-defined signal 1. This signal, like [`UserSignal2`], does not have a predefined meaning and is not produced by the OS. For this reason, it is typically used for interprocess communication between two programs familiar with each other, or in language runtimes to signal certain events, such as externally activated immediate garbage collection.
931    ///
932    /// *Default handler: process termination.*
933    ///
934    /// [`UserSignal2`]: #variant.UserSignal2 " "
935    #[cfg(any(doc, se_full_posix_1990))]
936    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
937        feature = "doc_cfg",
938        doc(cfg(not(target_os = "hermit"))),
939    )]
940    UserSignal1 = SIGUSR1,
941    /// `SIGUSR2` – user-defined signal 2. This signal is similar to [`UserSignal1`] and has the same properties, but is a distinct signal nonetheless.
942    ///
943    /// *Default handler: process termination.*
944    ///
945    /// [`UserSignal1`]: #variant.UserSignal1 " "
946    #[cfg(any(doc, se_full_posix_1990))]
947    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
948        feature = "doc_cfg",
949        doc(cfg(not(target_os = "hermit"))),
950    )]
951    UserSignal2 = SIGUSR2,
952    /// `SIGCHLD` – child process suspended, resumed or terminated. This signal is issued by the OS whenever a child process is suspended/resumed or terminated by a signal or otherwise.
953    ///
954    /// *Default handler: ignore.*
955    #[cfg(any(doc, se_full_posix_1990))]
956    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
957        feature = "doc_cfg",
958        doc(cfg(not(target_os = "hermit"))),
959    )]
960    ChildProcessEvent = SIGCHLD,
961    /// `SIGCONT` – resume the process after being suspended. This signal can be sent to a process by an external program when it wishes to resume that process after it being suspended in a stopped state.
962    ///
963    /// *Default handler: continue execution.*
964    #[cfg(any(doc, se_full_posix_1990))]
965    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
966        feature = "doc_cfg",
967        doc(cfg(not(target_os = "hermit"))),
968    )]
969    Continue = SIGCONT,
970    /// `SIGSTOP` – forcefully stop a process temporarily. This signal can only be sent to a process by an external program. Unlike [`Suspend`], this signal cannot be masked out or handled, i.e. it is guaranteed to be able to temporarily stop a process from executing without [forcefully terminating it]. The process can then be restarted using [`Continue`].
971    ///
972    /// *Default handler: temporarily stop process, **cannot be overriden or disabled**.*
973    ///
974    /// [`Suspend`]: #variant.Suspend " "
975    /// [forcefully terminating it]: #variant.Kill " "
976    /// [`Continue`]: #variant.Continue " "
977    #[cfg(any(doc, se_full_posix_1990))]
978    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
979        feature = "doc_cfg",
980        doc(cfg(not(target_os = "hermit"))),
981    )]
982    ForceSuspend = SIGSTOP,
983    /// `SIGTSTP` – temporarily stop a process. This signal can only be sent to a process by an external program. Unlike [`ForceSuspend`], this signal can be masked out or handled by the process which is requested to stop. The process can then be restarted using [`Continue`].
984    ///
985    /// *Default handler: temporarily stop process.*
986    ///
987    /// [`ForceSuspend`]: #variant.ForceSuspend " "
988    /// [`Continue`]: #variant.Continue " "
989    #[cfg(any(doc, se_full_posix_1990))]
990    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
991        feature = "doc_cfg",
992        doc(cfg(not(target_os = "hermit"))),
993    )]
994    Suspend = SIGTSTP,
995    /// `SIGTTIN` – attempt to read from standard input while in the background. This signal is issued by the OS whenever a process which is under [job control] tries to read from standard input but is in the background, i.e. temporarily detached from the terminal.
996    ///
997    /// *Default handler: temporarily stop process.*
998    ///
999    /// [job control]: https://en.wikipedia.org/wiki/Job_control_(Unix) " "
1000    #[cfg(any(doc, se_full_posix_1990))]
1001    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
1002        feature = "doc_cfg",
1003        doc(cfg(not(target_os = "hermit"))),
1004    )]
1005    TerminalInputWhileInBackground = SIGTTIN,
1006    /// `SIGTTOU` – attempt to write to standard output while in the background. This signal is issued by the OS whenever a process which is under [job control] tries to write to standard input but is in the background, i.e. temporarily detached from the terminal.
1007    ///
1008    /// *Default handler: temporarily stop process.*
1009    ///
1010    /// [job control]: https://en.wikipedia.org/wiki/Job_control_(Unix) " "
1011    #[cfg(any(doc, se_full_posix_1990))]
1012    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 templat
1013        feature = "doc_cfg",
1014        doc(cfg(not(target_os = "hermit"))),
1015    )]
1016    TerminalOutputWhileInBackground = SIGTTOU,
1017    /// `SIGPOLL` – watched file descriptor event. This signal is issued by the OS when a file descriptor which has been enabled to interact with this signal has a state update.
1018    ///
1019    /// *Default handler: process termination.*
1020    // TODO more on this
1021    #[cfg(any(se_sigpoll, se_sigpoll_is_sigio))]
1022    #[cfg_attr( // any(se_sigpoll, se_sigpoll_is_sigio) template
1023        feature = "doc_cfg",
1024        doc(cfg(any(
1025            target_os = "linux",
1026            target_os = "android",
1027            target_os = "emscripten",
1028            target_os = "redox",
1029            target_os = "haiku",
1030            target_os = "solaris",
1031            target_os = "illumos"
1032        )))
1033    )]
1034    PollNotification = SIGPOLL,
1035    /// `SIGBUS` – [bus error]. This signal is issued by the OS when a process does one of the following:
1036    /// - **Tries to access an invalid physical address**. Normally, this should never happen – attempts to access invalid *virtual* memory are handled as [segmentation faults], and invalid phyiscal addresses are typically not present in the address space of a program in user-mode.
1037    /// - **Performs an incorrectly aligned memory access**. In Rust, this can only happen if unsafe code is misused to construct an incorrectly aligned pointer to a type which requires alignment which is more strict than simple one byte alignment. This is a direct sign of memory unsafety being invoked.
1038    /// - **Incorrect x86 segment register**. This can only be acheieved using inline assembly or FFI (calling an external function written in assembly language or with usage of C/C++ inline assembly), and only on the x86 architecture. If an invalid value is loaded into the segment registers, the CPU generates this exception. This is either a sign of a failed advanced unsafe operation or a deliberate attempt to cryptically crash the program.
1039    ///
1040    /// For reasons described above, **this signal is considered unsafe** – handling it requires using `set_unsafe_handler`.
1041    ///
1042    /// *Default handler: process termination with a core dump.*
1043    ///
1044    /// [bus error]: https://en.wikipedia.org/wiki/Bus_error " "
1045    /// [segmentation faults]: #variant.SegmentationFault " "
1046    #[cfg(any(doc, se_base_posix_2001))]
1047    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
1048        feature = "doc_cfg",
1049        doc(cfg(not(target_os = "hermit"))),
1050    )]
1051    MemoryBusError = SIGBUS,
1052    /// `SIGPROF` – profiler clock signal. This signal is issued by the OS when the arranged amount of CPU time expires. The time includes not only user-mode CPU time spent in the process, but also kernel-mode CPU time which the OS associates with the process. This is different from [`UserModeProfilerClock`]'s behavior, which counts only user-mode CPU time. This clock can be set using the [`setitimer`] system call.
1053    ///
1054    /// *Default handler: process termination.*
1055    ///
1056    /// [`UserModeProfilerClock`]: #variant.UserModeProfilerClock " "
1057    /// [`setitimer`]: https://www.man7.org/linux/man-pages/man2/setitimer.2.html " "
1058    #[cfg(any(doc, se_base_posix_2001))]
1059    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
1060        feature = "doc_cfg",
1061        doc(cfg(not(target_os = "hermit"))),
1062    )]
1063    ProfilerClock = SIGPROF,
1064    /// `SIGVTALRM` – user-mode profiler clock signal. This signal is issued by the OS when the arranged amount of CPU time expires. Only user-mode CPU time is counted, in contrast to `ProfilerClock`, which counts kernel-mode time associated by the system with the process as well. This clock can be set using the [`setitimer`] system call.
1065    ///
1066    /// *Default handler: process termination.*
1067    ///
1068    /// [`ProfilerClock`]: #variant.ProfilerClock " "
1069    /// [`setitimer`]: https://www.man7.org/linux/man-pages/man2/setitimer.2.html " "
1070    #[cfg(any(doc, se_base_posix_2001))]
1071    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
1072        feature = "doc_cfg",
1073        doc(cfg(not(target_os = "hermit"))),
1074    )]
1075    UserModeProfilerClock = SIGVTALRM,
1076    /// `SIGSYS` – attempt to perform an invalid system call. This signal is issued by the OS when a system call receives invalid arguments. Normally, the C library functions used to perform system calls in Rust programs do not generate this signal – the only way to generate it is to send it to a process explicitly, use raw system call instructions or violate [`seccomp`] rules if it is enabled.
1077    ///
1078    /// *Default handler: process termination with a core dump.*
1079    ///
1080    /// [`seccomp`]: https://en.wikipedia.org/wiki/Seccomp " "
1081    #[cfg(any(doc, se_base_posix_2001))]
1082    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
1083        feature = "doc_cfg",
1084        doc(cfg(not(target_os = "hermit"))),
1085    )]
1086    InvalidSystemCall = SIGSYS,
1087    /// `SIGTRAP` – software breakpoint. This signal is issued by the OS when a breakpoint instruction is executed. On x86, the instruction to do so is `int 3`. This instruction is typically inserted by debuggers and code injection utilities.
1088    ///
1089    /// *Default handler: process termination with a core dump.*
1090    #[cfg(any(doc, se_base_posix_2001))]
1091    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
1092        feature = "doc_cfg",
1093        doc(cfg(not(target_os = "hermit"))),
1094    )]
1095    Breakpoint = SIGTRAP,
1096    /// `SIGURG` – [out-of-band data] received on a socket. This signal is issued by the OS when a socket owned by the process receives urgent out-of-band data.
1097    ///
1098    /// *Default handler: ignore.*
1099    ///
1100    /// [out-of-band data]: https://en.wikipedia.org/wiki/Out-of-band_data " "
1101    #[cfg(any(doc, se_base_posix_2001))]
1102    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
1103        feature = "doc_cfg",
1104        doc(cfg(not(target_os = "hermit"))),
1105    )]
1106    OutOfBandDataAvailable = SIGURG,
1107    /// `SIGXCPU` – assigned CPU time limit for the process was exceeded. This signal is issued by the OS if a CPU time limit for the process was set, when that limit expires. If not handled quickly, the system will issue a [`Kill`] signal to shut down the process forcefully, i.e. ignoring this signal won't lead to bypassing the limit. The [`setrlimit`] system call is used to set the soft limit for this signal and the hard limit, which invokes [`Kill`].
1108    ///
1109    /// *Default handler: process termination with a core dump.*
1110    ///
1111    /// [`setrlimit`]: https://www.man7.org/linux/man-pages/man2/setrlimit.2.html " "
1112    /// [`Kill`]: #variant.Kill " "
1113    #[cfg(any(doc, se_base_posix_2001))]
1114    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
1115        feature = "doc_cfg",
1116        doc(cfg(not(target_os = "hermit"))),
1117    )]
1118    CpuTimeLimitExceeded = SIGXCPU,
1119    /// `SIGXFSZ` – assigned file size limit for the process was exceeded. This signal is issued by the OS if a limit on the size of files which are written to by the process was set, when that limit is exceeded by the process. If ignored/handled, the offending system call fails with an error regardless of the handling method. The [`setrlimit`] system call is used to set the limit.
1120    ///
1121    /// *Default handler: process termination with a core dump.*
1122    ///
1123    /// [`setrlimit`]: https://www.man7.org/linux/man-pages/man2/setrlimit.2.html " "
1124    #[cfg(any(doc, se_base_posix_2001))]
1125    #[cfg_attr( // se_full_posix_1990/se_base_posix_2001 template
1126        feature = "doc_cfg",
1127        doc(cfg(not(target_os = "hermit"))),
1128    )]
1129    FileSizeLimitExceeded = SIGXFSZ,
1130}
1131impl SignalType {
1132    /// Returns `true` if the value is a special signal which cannot be blocked or handled ([`Kill`] or [`ForceSuspend`]), `false` otherwise.
1133    ///
1134    /// [`Kill`]: #variant.Kill " "
1135    /// [`ForceSuspend`]: #variant.ForceSuspend " "
1136    pub const fn is_unblockable(self) -> bool {
1137        matches!(self, Self::Kill | Self::ForceSuspend)
1138    }
1139    /// Returns `true` if the value is an unsafe signal which requires unsafe code when setting a handling method, `false` otherwise.
1140    pub const fn is_unsafe(self) -> bool {
1141        matches!(
1142            self,
1143            Self::SegmentationFault | Self::MemoryBusError | Self::IllegalInstruction
1144        )
1145    }
1146}
1147impl From<SignalType> for i32 {
1148    fn from(op: SignalType) -> Self {
1149        op as i32
1150    }
1151}
1152impl From<SignalType> for u32 {
1153    fn from(op: SignalType) -> Self {
1154        op as u32
1155    }
1156}
1157impl TryFrom<i32> for SignalType {
1158    type Error = UnknownSignalError;
1159    #[rustfmt::skip]
1160    fn try_from(value: i32) -> Result<Self, Self::Error> {
1161        match value {
1162            #[cfg(se_basic)] SIGHUP => Ok(Self::Hangup),
1163            #[cfg(se_basic)] SIGINT => Ok(Self::KeyboardInterrupt),
1164            #[cfg(se_basic)] SIGQUIT => Ok(Self::QuitAndDump),
1165            #[cfg(se_basic)] SIGILL => Ok(Self::IllegalInstruction),
1166            #[cfg(se_basic)] SIGABRT => Ok(Self::Abort),
1167            #[cfg(se_basic)] SIGFPE => Ok(Self::MathException),
1168            #[cfg(se_basic)] SIGKILL => Ok(Self::Kill),
1169            #[cfg(se_basic)] SIGSEGV => Ok(Self::SegmentationFault),
1170            #[cfg(se_basic)] SIGPIPE => Ok(Self::BrokenPipe),
1171            #[cfg(se_basic)] SIGALRM => Ok(Self::AlarmClock),
1172            #[cfg(se_basic)] SIGTERM => Ok(Self::Termination),
1173            #[cfg(se_full_posix_1990)] SIGUSR1 => Ok(Self::UserSignal1),
1174            #[cfg(se_full_posix_1990)] SIGUSR2 => Ok(Self::UserSignal2),
1175            #[cfg(se_full_posix_1990)] SIGCHLD => Ok(Self::ChildProcessEvent),
1176            #[cfg(se_full_posix_1990)] SIGCONT => Ok(Self::Continue),
1177            #[cfg(se_full_posix_1990)] SIGSTOP => Ok(Self::ForceSuspend),
1178            #[cfg(se_full_posix_1990)] SIGTSTP => Ok(Self::Suspend),
1179            #[cfg(se_full_posix_1990)] SIGTTIN => Ok(Self::TerminalInputWhileInBackground),
1180            #[cfg(se_full_posix_1990)] SIGTTOU => Ok(Self::TerminalOutputWhileInBackground),
1181            #[cfg(any(se_sigpoll, se_sigpoll_is_sigio))] SIGPOLL => Ok(Self::PollNotification),
1182            #[cfg(se_full_posix_2001)] SIGBUS => Ok(Self::MemoryBusError),
1183            #[cfg(se_full_posix_2001)] SIGPROF => Ok(Self::ProfilerClock),
1184            #[cfg(se_base_posix_2001)] SIGSYS => Ok(Self::InvalidSystemCall),
1185            #[cfg(se_base_posix_2001)] SIGTRAP => Ok(Self::Breakpoint),
1186            #[cfg(se_base_posix_2001)] SIGURG => Ok(Self::OutOfBandDataAvailable),
1187            #[cfg(se_base_posix_2001)] SIGVTALRM => Ok(Self::UserModeProfilerClock),
1188            #[cfg(se_base_posix_2001)] SIGXCPU => Ok(Self::CpuTimeLimitExceeded),
1189            #[cfg(se_base_posix_2001)] SIGXFSZ => Ok(Self::FileSizeLimitExceeded),
1190            _ => Err(UnknownSignalError { value }),
1191        }
1192    }
1193}
1194impl TryFrom<u32> for SignalType {
1195    type Error = UnknownSignalError;
1196    fn try_from(value: u32) -> Result<Self, Self::Error> {
1197        value.try_into()
1198    }
1199}
1200
1201/// Error type returned when a conversion from [`i32`]/[`u32`] to [`SignalType`] fails.
1202///
1203/// [`i32`]: https://doc.rust-lang.org/std/primitive.i32.html " "
1204/// [`u32`]: https://doc.rust-lang.org/std/primitive.u32.html " "
1205/// [`SignalType`]: enum.SignalType.html " "
1206#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1207pub struct UnknownSignalError {
1208    /// The unknown signal value which was encountered.
1209    pub value: i32,
1210}
1211impl Display for UnknownSignalError {
1212    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1213        write!(f, "unknown signal value {}", self.value)
1214    }
1215}
1216impl fmt::Binary for UnknownSignalError {
1217    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1218        write!(f, "unknown signal value {:b}", self.value)
1219    }
1220}
1221impl fmt::LowerHex for UnknownSignalError {
1222    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1223        write!(f, "unknown signal value {:x}", self.value)
1224    }
1225}
1226impl fmt::UpperExp for UnknownSignalError {
1227    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1228        write!(f, "unknown signal value {:X}", self.value)
1229    }
1230}
1231impl fmt::Octal for UnknownSignalError {
1232    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1233        write!(f, "unknown signal value {:o}", self.value)
1234    }
1235}
1236impl Error for UnknownSignalError {}