1use std::process::Child;
8use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
9use std::sync::{Arc, OnceLock};
10
11use anyhow::{Result, anyhow};
12use nix::sys::signal::{Signal, killpg};
13use nix::unistd::Pid;
14use signal_hook::consts::{SIGHUP, SIGINT, SIGQUIT, SIGTERM};
15
16use super::cpu;
17
18pub struct Group {
19 pgid: u32,
20}
21
22impl Group {
23 pub fn of(child: &Child) -> Self {
25 Self { pgid: child.id() }
26 }
27
28 fn signal(&self, signal: Signal) {
29 if let Ok(pgid) = i32::try_from(self.pgid) {
30 let _ = killpg(Pid::from_raw(pgid), signal);
31 }
32 }
33
34 pub fn freeze(&self) {
37 self.signal(Signal::SIGSTOP);
38 }
39
40 pub fn kill(&self) {
44 self.signal(Signal::SIGKILL);
45 }
46
47 pub fn members(&self) -> Vec<u32> {
48 cpu::group_members(self.pgid)
49 }
50
51 pub fn thread_states(&self) -> Vec<String> {
55 self.members().into_iter().flat_map(task_states).collect()
56 }
57}
58
59fn task_states(pid: u32) -> Vec<String> {
60 std::fs::read_dir(format!("/proc/{pid}/task"))
61 .into_iter()
62 .flatten()
63 .flatten()
64 .filter_map(|entry| {
65 let wchan = std::fs::read_to_string(entry.path().join("wchan")).ok()?;
66 (!wchan.is_empty())
67 .then(|| format!(" pid {pid} tid {:?}: {wchan}", entry.file_name()))
68 })
69 .collect()
70}
71
72struct Signals {
76 requested: Arc<AtomicBool>,
77 idle: Arc<AtomicBool>,
78 holders: AtomicUsize,
79}
80
81static SIGNALS: OnceLock<Result<Signals, String>> = OnceLock::new();
82
83fn install() -> Result<Signals, String> {
84 let requested = Arc::new(AtomicBool::new(false));
85 let idle = Arc::new(AtomicBool::new(true));
86 for signal in [SIGHUP, SIGINT, SIGQUIT, SIGTERM] {
87 signal_hook::flag::register_conditional_default(signal, Arc::clone(&idle))
88 .and_then(|_| signal_hook::flag::register(signal, Arc::clone(&requested)))
89 .map_err(|err| err.to_string())?;
90 }
91 Ok(Signals {
92 requested,
93 idle,
94 holders: AtomicUsize::new(0),
95 })
96}
97
98pub struct Termination {
106 signals: &'static Signals,
107}
108
109impl Termination {
110 pub fn watch() -> Result<Self> {
111 let signals = SIGNALS
112 .get_or_init(install)
113 .as_ref()
114 .map_err(|err| anyhow!("cannot watch for termination signals: {err}"))?;
115 if signals.holders.fetch_add(1, Ordering::SeqCst) == 0 {
116 signals.requested.store(false, Ordering::SeqCst);
117 }
118 signals.idle.store(false, Ordering::SeqCst);
119 Ok(Self { signals })
120 }
121
122 pub fn requested(&self) -> bool {
123 self.signals.requested.load(Ordering::SeqCst)
124 }
125}
126
127impl Drop for Termination {
128 fn drop(&mut self) {
129 if self.signals.holders.fetch_sub(1, Ordering::SeqCst) == 1 {
130 self.signals.idle.store(true, Ordering::SeqCst);
131 }
132 }
133}
134
135#[cfg(test)]
136mod tests;