cdp_html_shot/exit_hook.rs
1use std::sync::{Arc, Once};
2
3pub struct ExitHook {
4 func: Arc<dyn Fn() + Send + Sync>,
5}
6
7impl ExitHook {
8 pub fn new<F: Fn() + Send + Sync + 'static>(f: F) -> Self {
9 Self { func: Arc::new(f) }
10 }
11
12 pub fn register(&self) -> Result<(), Box<dyn std::error::Error>> {
13 static ONCE: Once = Once::new();
14 let f = self.func.clone();
15 let res = Ok(());
16 ONCE.call_once(|| {
17 if let Err(e) = ctrlc::set_handler(move || {
18 f();
19 std::process::exit(0);
20 }) {
21 eprintln!("Ctrl+C handler error: {}", e);
22 }
23 });
24 res
25 }
26}
27
28impl Drop for ExitHook {
29 fn drop(&mut self) {
30 (self.func)();
31 }
32}