Skip to main content

a3s_box_runtime/
process.rs

1//! Host process identity helpers shared by runtime consumers.
2
3/// Check whether a host process exists.
4///
5/// On Unix, `EPERM` still means the process exists even though the caller is
6/// not allowed to signal it.
7#[cfg(unix)]
8pub fn is_process_alive(pid: u32) -> bool {
9    let Ok(pid) = i32::try_from(pid) else {
10        return false;
11    };
12    let result = unsafe { libc::kill(pid, 0) };
13    result == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
14}
15
16#[cfg(windows)]
17pub fn is_process_alive(pid: u32) -> bool {
18    use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE};
19    use windows_sys::Win32::System::Threading::{
20        GetExitCodeProcess, OpenProcess, PROCESS_QUERY_INFORMATION,
21    };
22
23    unsafe {
24        let handle = OpenProcess(PROCESS_QUERY_INFORMATION, 0, pid);
25        if handle == 0 {
26            return false;
27        }
28        let mut exit_code = 0u32;
29        let ok = GetExitCodeProcess(handle, &mut exit_code);
30        CloseHandle(handle);
31        ok != 0 && exit_code == STILL_ACTIVE as u32
32    }
33}
34
35#[cfg(not(any(unix, windows)))]
36pub fn is_process_alive(_pid: u32) -> bool {
37    false
38}
39
40/// Read a process's Linux start time as a stable PID identity token.
41///
42/// The value is field 22 of `/proc/<pid>/stat`, measured in clock ticks since
43/// boot. It distinguishes a recorded process from a later process that reused
44/// the same PID. Other platforms return `None` until they provide an equivalent
45/// stable token.
46#[cfg(target_os = "linux")]
47pub fn pid_start_time(pid: u32) -> Option<u64> {
48    let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
49    linux_process_identity_from_stat(&stat).map(|(_, start_time)| start_time)
50}
51
52#[cfg(not(target_os = "linux"))]
53pub fn pid_start_time(_pid: u32) -> Option<u64> {
54    None
55}
56
57/// Check process liveness and, when recorded, its stable identity token.
58///
59/// Records created before PID identity tokens were introduced contain no
60/// expected start time and retain their legacy liveness behavior.
61pub fn is_process_alive_with_identity(pid: u32, expected_start_time: Option<u64>) -> bool {
62    if !is_process_alive(pid) {
63        return false;
64    }
65
66    match expected_start_time {
67        Some(expected) => pid_start_time(pid) == Some(expected),
68        None => true,
69    }
70}
71
72/// Check whether a process identity is actively running rather than a zombie.
73///
74/// A completed child remains addressable by `kill(pid, 0)` until its parent
75/// reaps it. Lifecycle ownership still uses [`is_process_alive_with_identity`]
76/// when that distinction matters; completion waiters use this helper so a
77/// fully drained worker zombie is treated as finished immediately.
78#[cfg(target_os = "linux")]
79pub fn is_process_running_with_identity(pid: u32, expected_start_time: Option<u64>) -> bool {
80    let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) else {
81        return false;
82    };
83    linux_process_identity_from_stat(&stat).is_some_and(|(state, start_time)| {
84        state != 'Z'
85            && expected_start_time
86                .map(|expected| expected == start_time)
87                .unwrap_or(true)
88    })
89}
90
91#[cfg(not(target_os = "linux"))]
92pub fn is_process_running_with_identity(pid: u32, expected_start_time: Option<u64>) -> bool {
93    is_process_alive_with_identity(pid, expected_start_time)
94}
95
96/// Wait for a Linux process identity to disappear, reaping it when it is an
97/// exited child of the current process.
98///
99/// Recovered runtime handles retain only a durable PID/start-time pair. When a
100/// worker was originally spawned by this process, dropping its `Child` handle
101/// does not transfer wait ownership: the completed worker remains a zombie
102/// until an explicit `waitpid`. Workers inherited by another process cannot be
103/// reaped here, so this helper waits for their owner to reap them instead.
104#[cfg(target_os = "linux")]
105pub(crate) fn wait_for_process_exit_with_identity(
106    pid: u32,
107    expected_start_time: u64,
108    timeout: std::time::Duration,
109) -> bool {
110    let Ok(raw_pid) = i32::try_from(pid) else {
111        return false;
112    };
113    let deadline = std::time::Instant::now() + timeout;
114    loop {
115        if !is_process_alive_with_identity(pid, Some(expected_start_time)) {
116            return true;
117        }
118        if !is_process_running_with_identity(pid, Some(expected_start_time)) {
119            let mut status = 0;
120            let waited = unsafe { libc::waitpid(raw_pid, &mut status, libc::WNOHANG) };
121            if waited == raw_pid || !is_process_alive_with_identity(pid, Some(expected_start_time))
122            {
123                return true;
124            }
125        }
126        if std::time::Instant::now() >= deadline {
127            return false;
128        }
129        std::thread::sleep(std::time::Duration::from_millis(10));
130    }
131}
132
133#[cfg(target_os = "linux")]
134fn linux_process_identity_from_stat(stat: &str) -> Option<(char, u64)> {
135    // `comm` may contain spaces and parentheses, so fields begin after the
136    // final `)`. Field 3 is then token zero and field 22 is token 19.
137    let fields: Vec<&str> = stat
138        .get(stat.rfind(')')? + 1..)?
139        .split_whitespace()
140        .collect();
141    let state = fields.first()?.chars().next()?;
142    let start_time = fields.get(19)?.parse().ok()?;
143    Some((state, start_time))
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    #[test]
151    fn current_process_is_alive() {
152        assert!(is_process_alive(std::process::id()));
153    }
154
155    #[test]
156    fn missing_process_is_not_alive() {
157        assert!(!is_process_alive(0x7fff_fffe));
158    }
159
160    #[cfg(target_os = "linux")]
161    #[test]
162    fn parses_start_time_after_complex_command_name() {
163        let stat =
164            "123 (command (with) spaces) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 4242";
165        assert_eq!(linux_process_identity_from_stat(stat), Some(('S', 4242)));
166        assert_eq!(linux_process_identity_from_stat("malformed"), None);
167        assert_eq!(linux_process_identity_from_stat("123 (short) S 1"), None);
168    }
169
170    #[cfg(target_os = "linux")]
171    #[test]
172    fn identity_rejects_a_reused_pid() {
173        let pid = std::process::id();
174        let start_time = pid_start_time(pid);
175        assert!(start_time.is_some());
176        assert!(is_process_alive_with_identity(pid, start_time));
177        assert!(!is_process_alive_with_identity(pid, Some(u64::MAX)));
178        assert!(is_process_alive_with_identity(pid, None));
179        assert!(!is_process_alive_with_identity(0x7fff_fffe, None));
180        assert!(is_process_running_with_identity(pid, start_time));
181    }
182
183    #[cfg(target_os = "linux")]
184    #[test]
185    fn parses_zombie_state_for_completion_waiters() {
186        let stat = "123 (completed worker) Z 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 4242";
187        assert_eq!(linux_process_identity_from_stat(stat), Some(('Z', 4242)));
188    }
189
190    #[cfg(target_os = "linux")]
191    #[test]
192    #[allow(clippy::zombie_processes)] // Deliberately drop Child to exercise recovered waitpid.
193    fn recovered_identity_reaps_an_exited_child() {
194        let child = std::process::Command::new("true").spawn().unwrap();
195        let pid = child.id();
196        let start_time = pid_start_time(pid).unwrap();
197        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1);
198        while is_process_running_with_identity(pid, Some(start_time))
199            && std::time::Instant::now() < deadline
200        {
201            std::thread::sleep(std::time::Duration::from_millis(5));
202        }
203
204        assert!(is_process_alive_with_identity(pid, Some(start_time)));
205        assert!(!is_process_running_with_identity(pid, Some(start_time)));
206        assert!(wait_for_process_exit_with_identity(
207            pid,
208            start_time,
209            std::time::Duration::from_secs(1),
210        ));
211        assert!(!is_process_alive_with_identity(pid, Some(start_time)));
212    }
213}