1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
use std::sync::{Arc, Mutex, OnceLock};
use tokio::sync::oneshot;
static INSTANCE: OnceLock<Arc<Mutex<CtrlCState>>> = OnceLock::new();
/// Provides Ctrl+C notifications, and allows suppressing the automatic termination
/// of the process.
///
/// Ctrl+C can only be suppressed "once at a time". Imagine the following scenario:
///
/// - You call `CtrlC::observe_oneshot()` and store the receiver in a variable
/// that remains alive for the upcoming long-running activity.
/// - The long-running is running.
/// - The user presses Ctrl+C. This sends a message to the receiver.
/// - You take your time reacting to the message, or you don't check it often enough.
/// - In the meantime, the user presses Ctrl+C again.
///
/// This second press terminates the process, which is what the user expects.
pub struct CtrlC;
impl CtrlC {
/// Returns a new [`oneshot::Receiver`] which will receive a message once
/// Ctrl+C is pressed.
///
/// Suspends the automatic termination for *one* Ctrl+C.
///
/// But the Ctrl+C after that will terminate again - unless `observe_oneshot`
/// has been called again since then.
///
/// Furthermore, once the receiver is dropped, Ctrl+C will also terminate the process.
///
/// ## Usage
///
/// ### Example 1: Suspend automatic termination for a given scope
///
/// ```
/// let mut ctrl_c_receiver = CtrlC::observe_oneshot();
///
/// // do something
/// // [...]
///
/// ctrl_c_receiver.close(); // Restores automatic termination behavior
/// ```
///
/// ### Example 2: Suspend automatic termination and check if Ctrl+C was pressed
///
/// ```
/// let mut ctrl_c_receiver = CtrlC::observe_oneshot();
///
/// // do something
/// // [...]
///
/// match ctrl_c_receiver.try_recv() {
/// Ok(()) => {
/// // Ctrl+C was pressed once. If it had been pressed another time then we wouldn't
/// // be here because the process would already have terminated.
/// }
/// Err(TryRecvError::Empty) => {
/// // Ctrl+C was not pressed.
/// }
/// Err(TryRecvError::Closed) => {
/// // Someone else has called `CtrlC::observe_oneshot()` in the meantime and swapped
/// // out our handler.
/// // When our handler was active, Ctrl+C was not pressed.
/// }
/// }
/// ctrl_c_receiver.close(); // Restores automatic termination behavior
/// // Alternatively, just drop ctrl_c_receiver, or let it go out of scope.
/// ```
///
/// ### Example 3: Keep checking for Ctrl+C in a loop
///
/// ```
/// let mut ctrl_c_receiver = CtrlC::observe_oneshot();
///
/// loop {
/// if ctrl_c_receiver.try_recv().is_ok() {
/// // Ctrl+C was pressed once. Exit the loop.
/// // (If Ctrl+C had been pressed more than once then we wouldn't
/// // be here because the process would already have terminated.)
/// break;
/// }
///
/// // do something
/// // [...]
/// }
///
/// ctrl_c_receiver.close(); // Restores automatic termination behavior
/// // Alternatively, just drop ctrl_c_receiver, or let it go out of scope.
/// ```
///
/// ### Example 4: Loop on a future and stop early if Ctrl+C is pressed
///
/// ```
/// let mut ctrl_c_receiver = CtrlC::observe_oneshot();
///
/// loop {
/// tokio::select! {
/// ctrl_c_result = &mut ctrl_c_receiver => {
/// match ctrl_c_result {
/// Ok(()) => {
/// // Ctrl+C was pressed once. If it had been pressed another time then we wouldn't
/// // be here because the process would already have terminated.
/// }
/// Err(e) => {
/// // Someone else has called `CtrlC::observe_oneshot()` in the meantime and swapped
/// // out our handler.
/// // When our handler was active, Ctrl+C was not pressed.
/// }
/// }
/// }
/// something_else = some_other_future => {
/// // [...]
/// }
/// }
///
/// // do something
/// // [...]
/// }
///
/// ctrl_c_receiver.close(); // Restores automatic termination behavior
/// // Alternatively, just drop ctrl_c_receiver, or let it go out of scope.
/// ```
pub fn observe_oneshot() -> oneshot::Receiver<()> {
let (tx, rx) = oneshot::channel();
CtrlCState::get().lock().unwrap().current_sender = Some(tx);
rx
}
}
struct CtrlCState {
current_sender: Option<oneshot::Sender<()>>,
}
impl CtrlCState {
pub fn get() -> &'static Arc<Mutex<CtrlCState>> {
INSTANCE.get_or_init(|| {
ctrlc::set_handler(|| {
let sender = CtrlCState::get().lock().unwrap().current_sender.take();
if let Some(sender) = sender {
if let Ok(()) = sender.send(()) {
// The receiver still existed. Trust that it will handle this Ctrl+C.
// Do not terminate this process.
return;
}
}
// We get here if there is no current handler installed, or if the
// receiver has been destroyed.
// Terminate the process.
terminate_for_ctrl_c();
})
.expect("Couldn't install Ctrl+C handler");
Arc::new(Mutex::new(CtrlCState {
current_sender: None,
}))
})
}
}
fn terminate_for_ctrl_c() -> ! {
std::process::exit(1)
}