use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use signal_mod::{Coordinator, ShutdownHook, ShutdownReason};
struct CountedHook {
label: String,
priority: i32,
counter: Arc<AtomicUsize>,
}
impl ShutdownHook for CountedHook {
fn name(&self) -> &str {
&self.label
}
fn priority(&self) -> i32 {
self.priority
}
fn run(&self, reason: ShutdownReason) {
let prev = self.counter.fetch_add(1, Ordering::Relaxed);
println!(
"[{}] hook fired (priority={}, prev_count={}, reason={})",
self.label, self.priority, prev, reason,
);
}
}
fn main() {
let counter = Arc::new(AtomicUsize::new(0));
let coord = Coordinator::builder()
.hook(CountedHook {
label: "primary".into(),
priority: 200,
counter: Arc::clone(&counter),
})
.hook(CountedHook {
label: "secondary".into(),
priority: 0,
counter: Arc::clone(&counter),
})
.build();
coord.run_hooks(ShutdownReason::Requested);
coord.run_hooks(ShutdownReason::Forced);
println!("counter final value = {}", counter.load(Ordering::Relaxed));
}