1 #![doc(
2     test(attr(deny(warnings))),
3     test(attr(allow(bare_trait_objects, unknown_lints)))
4 )]
5 #![allow(
6     unknown_lints,
7     renamed_and_removed_lints,
8     intra_doc_link_resolution_failure,
9     broken_itra_doc_links
10 )]
11 //! Library for easier and safe Unix signal handling
12 //!
13 //! Unix signals are inherently hard to handle correctly, for several reasons:
14 //!
15 //! * They are a global resource. If a library wants to set its own signal handlers, it risks
16 //!   disturbing some other library. It is possible to chain the previous signal handler, but then
17 //!   it is impossible to remove the old signal handlers from the chains in any practical manner.
18 //! * They can be called from whatever thread, requiring synchronization. Also, as they can
19 //!   interrupt a thread at any time, making most handling race-prone.
20 //! * According to the POSIX standard, the set of functions one may call inside a signal handler is
21 //!   limited to very few of them. To highlight, mutexes (or other locking mechanisms) and memory
22 //!   allocation and deallocation is *not* allowed.
23 //!
24 //! This library aims to solve some of the problems. It provides a global registry of actions
25 //! performed on arrival of signals. It is possible to register multiple actions for the same
26 //! signal and it is possible to remove the actions later on. If there was a previous signal
27 //! handler when the first action for a signal is registered, it is chained (but the original one
28 //! can't be removed).
29 //!
30 //! The main function of the library is [`register`](fn.register.html).
31 //!
32 //! It also offers several common actions one might want to register, implemented in the correct
33 //! way. They are scattered through submodules and have the same limitations and characteristics as
34 //! the [`register`](fn.register.html) function. Generally, they work to postpone the action taken
35 //! outside of the signal handler, where the full freedom and power of rust is available.
36 //!
37 //! Unlike other Rust libraries for signal handling, this should be flexible enough to handle all
38 //! the common and useful patterns.
39 //!
40 //! The library avoids all the newer fancy signal-handling routines. These generally have two
41 //! downsides:
42 //!
43 //! * They are not fully portable, therefore the library would have to contain *both* the
44 //!   implementation using the basic routines and the fancy ones. As signal handling is not on the
45 //!   hot path of most programs, this would not bring any actual benefit.
46 //! * The other routines require that the given signal is masked in all application's threads. As
47 //!   the signals are not masked by default and a new thread inherits the signal mask of its
48 //!   parent, it is possible to guarantee such global mask by masking them before any threads
49 //!   start. While this is possible for an application developer to do, it is not possible for a
50 //!   a library.
51 //!
52 //! # Warning
53 //!
54 //! Even with this library, you should thread with care. It does not eliminate all the problems
55 //! mentioned above.
56 //!
57 //! Also, note that the OS may collate multiple instances of the same signal into just one call of
58 //! the signal handler. Furthermore, some abstractions implemented here also naturally collate
59 //! multiple instances of the same signal. The general guarantee is, if there was at least one
60 //! signal of the given number delivered, an action will be taken, but it is not specified how many
61 //! times ‒ signals work mostly as kind of „wake up now“ nudge, if the application is slow to wake
62 //! up, it may be nudged multiple times before it does so.
63 //!
64 //! # Signal limitations
65 //!
66 //! OS limits still apply ‒ it is not possible to redefine certain signals (eg. `SIGKILL` or
67 //! `SIGSTOP`) and it is probably a *very* stupid idea to touch certain other ones (`SIGSEGV`,
68 //! `SIGFPE`, `SIGILL`). Therefore, this library will panic if any attempt at manipulating these is
69 //! made. There are some use cases for redefining the latter ones, but these are not well served by
70 //! this library and you really *really* have to know what you're doing and are generally on your
71 //! own doing that.
72 //!
73 //! # Signal masks
74 //!
75 //! As the library uses `sigaction` under the hood, signal masking works as expected (eg. with
76 //! `pthread_sigmask`). This means, signals will *not* be delivered if the signal is masked in all
77 //! program's threads.
78 //!
79 //! By the way, if you do want to modify the signal mask (or do other Unix-specific magic), the
80 //! [nix](https://crates.io/crates/nix) crate offers safe interface to many low-level functions,
81 //! including
82 //! [`pthread_sigmask`](https://docs.rs/nix/0.11.0/nix/sys/signal/fn.pthread_sigmask.html).
83 //!
84 //! # Portability
85 //!
86 //! It should work on any POSIX.1-2001 system, which are all the major big OSes with the notable
87 //! exception of Windows.
88 //!
89 //! Non-standard signals are also supported. Pass the signal value directly from `libc` or use
90 //! the numeric value directly.
91 //!
92 //! ```rust
93 //! use std::sync::Arc;
94 //! use std::sync::atomic::{AtomicBool};
95 //! let term = Arc::new(AtomicBool::new(false));
96 //! let _ = signal_hook::flag::register(libc::SIGINT, Arc::clone(&term));
97 //! ```
98 //!
99 //! This crate includes a limited support for Windows, based on `signal`/`raise` in the CRT.
100 //! There are differences in both API and behavior:
101 //!
102 //! - `iterator` and `pipe` are not yet implemented.
103 //! - We have only a few signals: `SIGABRT`, `SIGABRT_COMPAT`, `SIGBREAK`,
104 //!   `SIGFPE`, `SIGILL`, `SIGINT`, `SIGSEGV` and `SIGTERM`.
105 //! - Due to lack of signal blocking, there's a race condition.
106 //!   After the call to `signal`, there's a moment where we miss a signal.
107 //!   That means when you register a handler, there may be a signal which invokes
108 //!   neither the default handler or the handler you register.
109 //! - Handlers registered by `signal` in Windows are cleared on first signal.
110 //!   To match behavior in other platforms, we re-register the handler each time the handler is
111 //!   called, but there's a moment where we miss a handler.
112 //!   That means when you receive two signals in a row, there may be a signal which invokes
113 //!   the default handler, nevertheless you certainly have registered the handler.
114 //!
115 //! Moreover, signals won't work as you expected. `SIGTERM` isn't actually used and
116 //! not all `Ctrl-C`s are turned into `SIGINT`.
117 //!
118 //! Patches to improve Windows support in this library are welcome.
119 //!
120 //! # Examples
121 //!
122 //! ```rust
123 //! extern crate signal_hook;
124 //!
125 //! use std::io::Error;
126 //! use std::sync::Arc;
127 //! use std::sync::atomic::{AtomicBool, Ordering};
128 //!
129 //! fn main() -> Result<(), Error> {
130 //!     let term = Arc::new(AtomicBool::new(false));
131 //!     signal_hook::flag::register(signal_hook::SIGTERM, Arc::clone(&term))?;
132 //!     while !term.load(Ordering::Relaxed) {
133 //!         // Do some time-limited stuff here
134 //!         // (if this could block forever, then there's no guarantee the signal will have any
135 //!         // effect).
136 //! #
137 //! #       // Hack to terminate the example, not part of the real code.
138 //! #       term.store(true, Ordering::Relaxed);
139 //!     }
140 //!     Ok(())
141 //! }
142 //! ```
143 //!
144 //! # Features
145 //!
146 //! * `mio-support`: The [`Signals` iterator](iterator/struct.Signals.html) becomes pluggable into
147 //!   mio 0.6.
148 //! * `mio-0_7-support`: The [`Signals` iterator](iterator/struct.Signals.html) becomes pluggable into
149 //!   mio 0.7.
150 //! * `tokio-support`: The [`Signals`](iterator/struct.Signals.html) can be turned into
151 //!   [`Async`](iterator/struct.Async.html), which provides a `Stream` interface for integration in
152 //!   the asynchronous world.
153 
154 #[cfg(feature = "tokio-support")]
155 extern crate futures;
156 extern crate libc;
157 #[cfg(feature = "mio-support")]
158 extern crate mio;
159 #[cfg(any(test, feature = "mio-0_7-support"))]
160 extern crate mio_0_7;
161 extern crate signal_hook_registry;
162 #[cfg(feature = "tokio-support")]
163 extern crate tokio_reactor;
164 
165 pub mod cleanup;
166 pub mod flag;
167 #[cfg(not(windows))]
168 pub mod iterator;
169 #[cfg(not(windows))]
170 pub mod pipe;
171 
172 #[cfg(not(windows))]
173 pub use libc::{
174     SIGABRT, SIGALRM, SIGBUS, SIGCHLD, SIGCONT, SIGFPE, SIGHUP, SIGILL, SIGINT, SIGIO, SIGKILL,
175     SIGPIPE, SIGPROF, SIGQUIT, SIGSEGV, SIGSTOP, SIGSYS, SIGTERM, SIGTRAP, SIGUSR1, SIGUSR2,
176     SIGWINCH,
177 };
178 
179 #[cfg(windows)]
180 pub use libc::{SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM};
181 
182 // NOTE: they perhaps deserve backport to libc.
183 #[cfg(windows)]
184 /// Same as `SIGABRT`, but the number is compatible to other platforms.
185 pub const SIGABRT_COMPAT: libc::c_int = 6;
186 #[cfg(windows)]
187 /// Ctrl-Break is pressed for Windows Console processes.
188 pub const SIGBREAK: libc::c_int = 21;
189 
190 pub use signal_hook_registry::{register, unregister, SigId, FORBIDDEN};
191