Skip to main content

wasi_virt_layer_cli/
ctrlc_handler.rs

1use std::sync::{Arc, Mutex, OnceLock};
2
3type CleanupFn = Box<dyn Fn() + Send + Sync>;
4
5static CLEANUPS: OnceLock<Arc<Mutex<Vec<CleanupFn>>>> = OnceLock::new();
6
7/// Initializes the Ctrl-C handler if it hasn't been initialized already.
8pub fn init() {
9    CLEANUPS.get_or_init(|| {
10        let cleanups = Arc::new(Mutex::new(Vec::<CleanupFn>::new()));
11        let cleanups_clone = cleanups.clone();
12
13        // We ignore errors if handler is already set
14        let _ = ctrlc::set_handler(move || {
15            if let Ok(guards) = cleanups_clone.lock() {
16                for guard in guards.iter().rev() {
17                    guard();
18                }
19            }
20            std::process::exit(130);
21        });
22
23        cleanups
24    });
25}
26
27/// Registers a cleanup function to be executed when a Ctrl-C signal is received.
28pub fn register(f: impl Fn() + Send + Sync + 'static) {
29    init(); // Ensure init
30    if let Some(cleanups) = CLEANUPS.get() {
31        cleanups.lock().unwrap().push(Box::new(f));
32    }
33}