a3s_box_runtime/
process.rs1#[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#[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
57pub 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#[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#[cfg(target_os = "linux")]
97fn linux_process_identity_from_stat(stat: &str) -> Option<(char, u64)> {
98 let fields: Vec<&str> = stat
101 .get(stat.rfind(')')? + 1..)?
102 .split_whitespace()
103 .collect();
104 let state = fields.first()?.chars().next()?;
105 let start_time = fields.get(19)?.parse().ok()?;
106 Some((state, start_time))
107}
108
109#[cfg(test)]
110mod tests {
111 use super::*;
112
113 #[test]
114 fn current_process_is_alive() {
115 assert!(is_process_alive(std::process::id()));
116 }
117
118 #[test]
119 fn missing_process_is_not_alive() {
120 assert!(!is_process_alive(0x7fff_fffe));
121 }
122
123 #[cfg(target_os = "linux")]
124 #[test]
125 fn parses_start_time_after_complex_command_name() {
126 let stat =
127 "123 (command (with) spaces) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 4242";
128 assert_eq!(linux_process_identity_from_stat(stat), Some(('S', 4242)));
129 assert_eq!(linux_process_identity_from_stat("malformed"), None);
130 assert_eq!(linux_process_identity_from_stat("123 (short) S 1"), None);
131 }
132
133 #[cfg(target_os = "linux")]
134 #[test]
135 fn identity_rejects_a_reused_pid() {
136 let pid = std::process::id();
137 let start_time = pid_start_time(pid);
138 assert!(start_time.is_some());
139 assert!(is_process_alive_with_identity(pid, start_time));
140 assert!(!is_process_alive_with_identity(pid, Some(u64::MAX)));
141 assert!(is_process_alive_with_identity(pid, None));
142 assert!(!is_process_alive_with_identity(0x7fff_fffe, None));
143 assert!(is_process_running_with_identity(pid, start_time));
144 }
145
146 #[cfg(target_os = "linux")]
147 #[test]
148 fn parses_zombie_state_for_completion_waiters() {
149 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";
150 assert_eq!(linux_process_identity_from_stat(stat), Some(('Z', 4242)));
151 }
152
153 #[cfg(target_os = "linux")]
154 #[test]
155 fn running_identity_treats_an_unreaped_child_as_finished() {
156 let mut child = std::process::Command::new("true").spawn().unwrap();
157 let pid = child.id();
158 let start_time = pid_start_time(pid).unwrap();
159 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(1);
160 while is_process_running_with_identity(pid, Some(start_time))
161 && std::time::Instant::now() < deadline
162 {
163 std::thread::sleep(std::time::Duration::from_millis(5));
164 }
165
166 assert!(is_process_alive_with_identity(pid, Some(start_time)));
167 assert!(!is_process_running_with_identity(pid, Some(start_time)));
168 child.wait().unwrap();
169 }
170}