tokio/signal/mod.rs
1//! Asynchronous signal handling for Tokio.
2//!
3//! Note that signal handling is in general a very tricky topic and should be
4//! used with great care. This crate attempts to implement 'best practice' for
5//! signal handling, but it should be evaluated for your own applications' needs
6//! to see if it's suitable.
7//!
8//! There are some fundamental limitations of this crate documented on the OS
9//! specific structures, as well.
10//!
11//! # Examples
12//!
13//! Print on "ctrl-c" notification.
14//!
15//! ```rust,no_run
16//! use tokio::signal;
17//!
18//! #[tokio::main]
19//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
20//! signal::ctrl_c().await?;
21//! println!("ctrl-c received!");
22//! Ok(())
23//! }
24//! ```
25//!
26//! Wait for `SIGHUP` on Unix
27//!
28//! ```rust,no_run
29//! # #[cfg(unix)] {
30//! use tokio::signal::unix::{signal, SignalKind};
31//!
32//! #[tokio::main]
33//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
34//! // An infinite stream of hangup signals.
35//! let mut stream = signal(SignalKind::hangup())?;
36//!
37//! // Print whenever a HUP signal is received
38//! loop {
39//! stream.recv().await;
40//! println!("got signal HUP");
41//! }
42//! }
43//! # }
44//! ```
45use crate::sync::watch::Receiver;
46use std::task::{Context, Poll};
47
48#[cfg(feature = "signal")]
49mod ctrl_c;
50#[cfg(feature = "signal")]
51pub use ctrl_c::ctrl_c;
52
53#[cfg(unix)]
54pub(crate) mod registry;
55
56pub mod unix;
57pub mod windows;
58
59mod reusable_box;
60use self::reusable_box::ReusableBoxFuture;
61
62#[derive(Debug)]
63struct RxFuture {
64 inner: ReusableBoxFuture<Receiver<()>>,
65}
66
67async fn make_future(mut rx: Receiver<()>) -> Receiver<()> {
68 rx.changed().await.expect("signal sender went away");
69 rx
70}
71
72impl RxFuture {
73 fn new(rx: Receiver<()>) -> Self {
74 Self {
75 inner: ReusableBoxFuture::new(make_future(rx)),
76 }
77 }
78
79 async fn recv(&mut self) {
80 use std::future::poll_fn;
81 poll_fn(|cx| self.poll_recv(cx)).await
82 }
83
84 fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<()> {
85 self.inner
86 .poll(cx)
87 .map(|rx| self.inner.set(make_future(rx)))
88 }
89}