Skip to main content

aft_base/
process_group.rs

1//! Process-group isolation and cleanup for deadline-bound subprocesses.
2
3#[cfg(windows)]
4use std::process::Stdio;
5use std::process::{Child, Command};
6
7/// Apply Unix-specific isolation so a kill() on timeout terminates
8/// grandchildren too (e.g. `sh -c 'sleep 60'` orphaning `sleep`).
9///
10/// Without this, killing the immediate child (`sh`) leaves `sleep`
11/// holding stdout/stderr pipes open, and the reader threads block
12/// until `sleep` terminates — turning a 2s timeout into a 60s hang.
13///
14/// The child leads a new process group whose id is its pid, which is all
15/// `kill_process_tree` needs for `killpg`. Use `process_group(0)`, never a
16/// `pre_exec` closure (such as a `setsid` call): std turns `process_group`
17/// into a `posix_spawn` attribute, while any `pre_exec` closure forces the
18/// fork+exec fallback. On macOS a fork of the large, many-threaded daemon
19/// takes every malloc zone lock, so every formatter run on an edit would
20/// stall allocation across the whole process.
21#[cfg(unix)]
22pub fn isolate_in_process_group(cmd: &mut Command) {
23    use std::os::unix::process::CommandExt;
24    cmd.process_group(0);
25}
26
27#[cfg(not(unix))]
28pub fn isolate_in_process_group(_cmd: &mut Command) {
29    // Best-effort no-op outside Unix. Windows timeout cleanup uses taskkill /T
30    // in kill_process_tree so .cmd wrappers and grandchildren are terminated.
31}
32
33/// Kill the child and, where supported, its entire process tree so wrapper
34/// scripts cannot leave descendants running after a timeout.
35#[cfg(unix)]
36pub fn kill_process_tree(child: &mut Child) {
37    let pid = child.id() as i32;
38    if pid > 0 {
39        // SAFETY: killpg with SIGKILL on a process group leader is safe.
40        // Negative pid form (kill -pgid) targets the whole group.
41        unsafe {
42            libc::killpg(pid, libc::SIGKILL);
43        }
44    }
45    let _ = child.kill();
46}
47
48#[cfg(windows)]
49pub fn kill_process_tree(child: &mut Child) {
50    let pid = child.id().to_string();
51    let _ = Command::new("taskkill")
52        .args(["/PID", pid.as_str(), "/T", "/F"])
53        .stdin(Stdio::null())
54        .stdout(Stdio::null())
55        .stderr(Stdio::null())
56        .status();
57    let _ = child.kill();
58}
59
60#[cfg(not(any(unix, windows)))]
61pub(crate) fn kill_process_tree(child: &mut Child) {
62    let _ = child.kill();
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[cfg(any(unix, windows))]
70    #[test]
71    fn isolated_child_can_be_killed_and_reaped() {
72        #[cfg(unix)]
73        let mut command = {
74            let mut command = Command::new("sh");
75            command.args(["-c", "sleep 60"]);
76            command
77        };
78        #[cfg(windows)]
79        let mut command = {
80            let mut command = Command::new("cmd");
81            command.args(["/C", "ping -n 60 127.0.0.1 >NUL"]);
82            command
83        };
84        isolate_in_process_group(&mut command);
85        let mut child = command.spawn().unwrap();
86        kill_process_tree(&mut child);
87        assert!(!child.wait().unwrap().success());
88    }
89}