Skip to main content

vtcode_bash_runner/
process_group.rs

1//! Process-group helpers for reliable child process cleanup.
2//!
3//! This module centralizes OS-specific pieces that ensure a spawned
4//! command can be cleaned up reliably:
5//! - `set_process_group` is called in `pre_exec` so the child starts its own
6//!   process group.
7//! - `detach_from_tty` starts a new session so non-interactive children do not
8//!   inherit the controlling TTY.
9//! - `kill_process_group_by_pid` targets the whole group (children/grandchildren)
10//!   instead of a single PID.
11//! - `kill_process_group` targets a known process group ID directly.
12//! - `set_parent_death_signal` (Linux only) arranges for the child to receive a
13//!   `SIGTERM` when the parent exits, and re-checks the parent PID to avoid
14//!   races during fork/exec.
15//! - `graceful_kill_process_group` sends SIGTERM, waits for a grace period, then
16//!   SIGKILL if still running.
17//!
18//! On non-Unix platforms these helpers are no-ops or adapted equivalents.
19//!
20//! Inspired by codex-rs/utils/pty process group management patterns.
21
22use std::io;
23
24#[cfg(windows)]
25mod windows;
26
27#[cfg(unix)]
28use nix::errno::Errno;
29#[cfg(target_os = "linux")]
30use nix::sys::prctl;
31#[cfg(unix)]
32use nix::sys::signal::{self, Signal};
33#[cfg(unix)]
34use nix::unistd::{self, Pid};
35#[cfg(unix)]
36use tokio::process::Child;
37
38/// Default grace period for graceful termination (milliseconds).
39pub const DEFAULT_GRACEFUL_TIMEOUT_MS: u64 = 500;
40
41/// Signal to send when killing process groups.
42#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
43pub enum KillSignal {
44    /// SIGINT - interrupt (Ctrl+C equivalent)
45    Int,
46    /// SIGTERM - allows graceful shutdown
47    Term,
48    /// SIGKILL - immediate termination
49    #[default]
50    Kill,
51}
52
53#[cfg(unix)]
54impl KillSignal {
55    fn as_nix_signal(self) -> Signal {
56        match self {
57            KillSignal::Int => Signal::SIGINT,
58            KillSignal::Term => Signal::SIGTERM,
59            KillSignal::Kill => Signal::SIGKILL,
60        }
61    }
62}
63
64#[cfg(unix)]
65#[cold]
66fn nix_err_to_io(err: Errno) -> io::Error {
67    io::Error::from_raw_os_error(err as i32)
68}
69
70/// Ensure the child receives SIGTERM when the original parent dies.
71///
72/// This should run in `pre_exec` and uses `parent_pid` captured before spawn to
73/// avoid a race where the parent exits between fork and exec.
74#[cfg(target_os = "linux")]
75pub fn set_parent_death_signal(parent_pid: libc::pid_t) -> io::Result<()> {
76    prctl::set_pdeathsig(Some(Signal::SIGTERM)).map_err(nix_err_to_io)?;
77
78    // Re-check parent PID to avoid race condition where parent exits between fork and exec.
79    if unistd::getppid() != Pid::from_raw(parent_pid) {
80        signal::kill(unistd::getpid(), Signal::SIGTERM).map_err(nix_err_to_io)?;
81    }
82
83    Ok(())
84}
85
86/// No-op on non-Linux platforms.
87#[cfg(not(target_os = "linux"))]
88pub fn set_parent_death_signal(_parent_pid: i32) -> io::Result<()> {
89    Ok(())
90}
91
92/// Detach from the controlling TTY by starting a new session.
93///
94/// This is useful for spawning background processes that should not receive
95/// signals from the controlling terminal.
96#[cfg(unix)]
97pub fn detach_from_tty() -> io::Result<()> {
98    match unistd::setsid() {
99        Ok(_) => Ok(()),
100        // EPERM means we're already a session leader, fall back to setpgid.
101        Err(Errno::EPERM) => set_process_group(),
102        Err(err) => Err(nix_err_to_io(err)),
103    }
104}
105
106/// No-op on non-Unix platforms.
107#[cfg(not(unix))]
108pub fn detach_from_tty() -> io::Result<()> {
109    Ok(())
110}
111
112/// Put the calling process into its own process group.
113///
114/// Intended for use in `pre_exec` so the child becomes the group leader.
115#[cfg(unix)]
116pub fn set_process_group() -> io::Result<()> {
117    unistd::setpgid(Pid::from_raw(0), Pid::from_raw(0)).map_err(nix_err_to_io)
118}
119
120/// No-op on non-Unix platforms.
121#[cfg(not(unix))]
122pub fn set_process_group() -> io::Result<()> {
123    Ok(())
124}
125
126/// Kill the process group for the given PID (best-effort).
127///
128/// This resolves the PGID for `pid` and sends SIGKILL to the whole group.
129#[cfg(unix)]
130pub fn kill_process_group_by_pid(pid: u32) -> io::Result<()> {
131    kill_process_group_by_pid_with_signal(pid, KillSignal::Kill)
132}
133
134/// Kill the process group for the given PID with a specific signal.
135#[cfg(unix)]
136pub fn kill_process_group_by_pid_with_signal(pid: u32, signal: KillSignal) -> io::Result<()> {
137    use std::io::ErrorKind;
138
139    let target_pid = Pid::from_raw(pid as libc::pid_t);
140    let pgid = unistd::getpgid(Some(target_pid));
141    let mut pgid_err = None;
142
143    match pgid {
144        Ok(group) => {
145            if let Err(err) = signal::killpg(group, signal.as_nix_signal()) {
146                let io_err = nix_err_to_io(err);
147                if io_err.kind() != ErrorKind::NotFound {
148                    pgid_err = Some(io_err);
149                }
150            }
151        }
152        Err(err) => pgid_err = Some(nix_err_to_io(err)),
153    }
154
155    // Always attempt to kill the direct child process handle as a fallback.
156    // This ensures termination even if the cached PGID was stale or
157    // the process group kill had issues.
158    match signal::kill(target_pid, signal.as_nix_signal()) {
159        Ok(()) => {}
160        // ESRCH means the target already exited and was reaped: nothing left
161        // to kill. Rust does not classify ESRCH as ErrorKind::NotFound on
162        // every host (including macOS) — see kill_process_group_with_signal —
163        // so match the errno itself instead of relying on ErrorKind.
164        Err(Errno::ESRCH) => return Ok(()),
165        Err(err) => {
166            let io_err = nix_err_to_io(err);
167            // If we have a pgid error and a direct kill error, prefer the pgid one.
168            if let Some(pgid_error) = pgid_err {
169                return Err(pgid_error);
170            }
171            return Err(io_err);
172        }
173    }
174
175    Ok(())
176}
177
178/// Use Windows' process-tree termination as the process-group equivalent.
179#[cfg(windows)]
180pub fn kill_process_group_by_pid(pid: u32) -> io::Result<()> {
181    kill_process(pid)
182}
183
184/// Use Windows' process-tree termination as the process-group equivalent.
185#[cfg(windows)]
186pub fn kill_process_group_by_pid_with_signal(pid: u32, _signal: KillSignal) -> io::Result<()> {
187    kill_process(pid)
188}
189
190/// No-op on platforms without process-group or process-tree support.
191#[cfg(all(not(unix), not(windows)))]
192pub fn kill_process_group_by_pid(_pid: u32) -> io::Result<()> {
193    Ok(())
194}
195
196/// No-op on platforms without process-group or process-tree support.
197#[cfg(all(not(unix), not(windows)))]
198pub fn kill_process_group_by_pid_with_signal(_pid: u32, _signal: KillSignal) -> io::Result<()> {
199    Ok(())
200}
201
202/// Kill a specific process group ID (best-effort).
203#[cfg(unix)]
204pub fn kill_process_group(process_group_id: u32) -> io::Result<()> {
205    kill_process_group_with_signal(process_group_id, KillSignal::Kill)
206}
207
208/// Kill a specific process group ID with a specific signal.
209#[cfg(unix)]
210pub fn kill_process_group_with_signal(process_group_id: u32, signal: KillSignal) -> io::Result<()> {
211    let pgid = Pid::from_raw(process_group_id as libc::pid_t);
212    if let Err(err) = signal::killpg(pgid, signal.as_nix_signal()) {
213        // ESRCH means cleanup has already completed. Rust does not classify
214        // it as ErrorKind::NotFound on every host (including macOS).
215        if err != Errno::ESRCH {
216            return Err(nix_err_to_io(err));
217        }
218    }
219
220    Ok(())
221}
222
223/// Use Windows' process-tree termination as the process-group equivalent.
224#[cfg(windows)]
225pub fn kill_process_group(process_group_id: u32) -> io::Result<()> {
226    kill_process(process_group_id)
227}
228
229/// Use Windows' process-tree termination as the process-group equivalent.
230#[cfg(windows)]
231pub fn kill_process_group_with_signal(process_group_id: u32, _signal: KillSignal) -> io::Result<()> {
232    kill_process(process_group_id)
233}
234
235/// No-op on platforms without process-group or process-tree support.
236#[cfg(all(not(unix), not(windows)))]
237pub fn kill_process_group(_process_group_id: u32) -> io::Result<()> {
238    Ok(())
239}
240
241/// No-op on platforms without process-group or process-tree support.
242#[cfg(all(not(unix), not(windows)))]
243pub fn kill_process_group_with_signal(_process_group_id: u32, _signal: KillSignal) -> io::Result<()> {
244    Ok(())
245}
246
247/// Kill the process group for a tokio child (best-effort).
248#[cfg(unix)]
249pub fn kill_child_process_group(child: &mut Child) -> io::Result<()> {
250    kill_child_process_group_with_signal(child, KillSignal::Kill)
251}
252
253/// Kill the process group for a tokio child with a specific signal.
254#[cfg(unix)]
255pub fn kill_child_process_group_with_signal(child: &mut Child, signal: KillSignal) -> io::Result<()> {
256    if let Some(pid) = child.id() {
257        return kill_process_group_by_pid_with_signal(pid, signal);
258    }
259
260    Ok(())
261}
262
263/// No-op on non-Unix platforms.
264#[cfg(not(unix))]
265pub fn kill_child_process_group(_child: &mut tokio::process::Child) -> io::Result<()> {
266    Ok(())
267}
268
269/// No-op on non-Unix platforms.
270#[cfg(not(unix))]
271pub fn kill_child_process_group_with_signal(_child: &mut tokio::process::Child, _signal: KillSignal) -> io::Result<()> {
272    Ok(())
273}
274
275/// Kill a process by PID on Windows.
276#[cfg(windows)]
277pub fn kill_process(pid: u32) -> io::Result<()> {
278    windows::kill_process(pid)
279}
280
281/// No-op on non-Windows platforms.
282#[cfg(not(windows))]
283pub fn kill_process(_pid: u32) -> io::Result<()> {
284    Ok(())
285}
286
287/// Result of a graceful termination attempt.
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub enum GracefulTerminationResult {
290    /// Process exited gracefully after SIGTERM/SIGINT.
291    GracefulExit,
292    /// Process had to be forcefully killed with SIGKILL.
293    ForcefulKill,
294    /// Process was already not running.
295    AlreadyExited,
296    /// Failed to check or terminate the process.
297    Error,
298}
299
300/// Check if a process (by PID) is still running.
301#[cfg(unix)]
302fn is_process_running(pid: u32) -> bool {
303    let target_pid = Pid::from_raw(pid as libc::pid_t);
304    match signal::kill(target_pid, None::<Signal>) {
305        Ok(()) => true,
306        // EPERM = exists but no permission (still running)
307        Err(Errno::EPERM) => true,
308        Err(_) => false,
309    }
310}
311
312#[cfg(not(unix))]
313fn is_process_running(_pid: u32) -> bool {
314    // On non-Unix, assume running (will fail gracefully)
315    true
316}
317
318/// Gracefully terminate a process group by PID.
319///
320/// This function implements a staged termination strategy:
321/// 1. Send the initial signal (default: SIGTERM, or SIGINT for interactive processes)
322/// 2. Wait up to `grace_period` for the process to exit
323/// 3. If still running, send SIGKILL
324///
325/// Returns information about how the termination completed.
326///
327/// # Arguments
328/// * `pid` - Process ID (will be used to resolve the process group)
329/// * `initial_signal` - Signal to try first (SIGINT, SIGTERM)
330/// * `grace_period` - How long to wait before SIGKILL
331#[cfg(unix)]
332pub fn graceful_kill_process_group(
333    pid: u32,
334    initial_signal: KillSignal,
335    grace_period: std::time::Duration,
336) -> GracefulTerminationResult {
337    // Check if already exited
338    if !is_process_running(pid) {
339        return GracefulTerminationResult::AlreadyExited;
340    }
341
342    // Resolve PGID
343    let target_pid = Pid::from_raw(pid as libc::pid_t);
344    let Ok(pgid) = unistd::getpgid(Some(target_pid)) else {
345        // Can't get PGID - process may have already exited.
346        return GracefulTerminationResult::AlreadyExited;
347    };
348
349    // Send initial signal (SIGTERM or SIGINT)
350    let signal = match initial_signal {
351        KillSignal::Kill => Signal::SIGTERM, // Don't send SIGKILL as initial.
352        other => other.as_nix_signal(),
353    };
354
355    if let Err(err) = signal::killpg(pgid, signal) {
356        if err != Errno::ESRCH {
357            return GracefulTerminationResult::Error;
358        }
359        return GracefulTerminationResult::AlreadyExited;
360    }
361
362    // Wait for graceful exit
363    let deadline = std::time::Instant::now() + grace_period;
364    let poll_interval = std::time::Duration::from_millis(10);
365
366    while std::time::Instant::now() < deadline {
367        if !is_process_running(pid) {
368            return GracefulTerminationResult::GracefulExit;
369        }
370        std::thread::sleep(poll_interval);
371    }
372
373    // Still running - force kill.
374    // Use the robust termination behavior from codex-rs/utils/pty PR 12688
375    // by attempting both a pgid kill and a direct pid kill.
376    let _ = signal::killpg(pgid, Signal::SIGKILL);
377    if let Err(err) = signal::kill(target_pid, Signal::SIGKILL) {
378        if err == Errno::ESRCH {
379            // Exited between check and kill.
380            return GracefulTerminationResult::GracefulExit;
381        }
382        return GracefulTerminationResult::Error;
383    }
384
385    GracefulTerminationResult::ForcefulKill
386}
387
388/// Graceful termination on non-Unix (best effort).
389///
390/// On Windows, uses `taskkill` without `/F` first, then retries with `/F`
391/// after the grace period.
392#[cfg(not(unix))]
393pub fn graceful_kill_process_group(
394    pid: u32,
395    initial_signal: KillSignal,
396    grace_period: std::time::Duration,
397) -> GracefulTerminationResult {
398    #[cfg(windows)]
399    {
400        let _ = initial_signal;
401        let pid_arg = pid.to_string();
402        match std::process::Command::new("taskkill").args(["/PID", &pid_arg, "/T"]).output() {
403            Ok(output) if output.status.success() => {
404                std::thread::sleep(grace_period);
405                match kill_process(pid) {
406                    Ok(()) => GracefulTerminationResult::ForcefulKill,
407                    Err(_) => GracefulTerminationResult::AlreadyExited,
408                }
409            }
410            Ok(_) => match kill_process(pid) {
411                Ok(()) => GracefulTerminationResult::ForcefulKill,
412                Err(_) => GracefulTerminationResult::AlreadyExited,
413            },
414            Err(_) => GracefulTerminationResult::Error,
415        }
416    }
417    #[cfg(not(windows))]
418    {
419        let _ = (pid, initial_signal, grace_period);
420        GracefulTerminationResult::Error
421    }
422}
423
424/// Gracefully terminate a process group with default settings.
425///
426/// Uses SIGTERM and the default grace period (500ms).
427pub fn graceful_kill_process_group_default(pid: u32) -> GracefulTerminationResult {
428    graceful_kill_process_group(pid, KillSignal::Term, std::time::Duration::from_millis(DEFAULT_GRACEFUL_TIMEOUT_MS))
429}
430
431/// Async-safe wrapper for graceful process-group termination.
432///
433/// This offloads the synchronous graceful-kill loop to Tokio's blocking pool so
434/// async runtime threads are not occupied by polling sleeps.
435pub async fn graceful_kill_process_group_default_async(pid: u32) -> GracefulTerminationResult {
436    tokio::task::spawn_blocking(move || graceful_kill_process_group_default(pid))
437        .await
438        .unwrap_or(GracefulTerminationResult::Error)
439}
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444
445    #[cfg(unix)]
446    #[test]
447    fn process_group_cleanup_is_idempotent_after_child_exit() {
448        use std::os::unix::process::CommandExt;
449        let mut child = std::process::Command::new("/bin/sh")
450            .args(["-c", "exit 0"])
451            .process_group(0)
452            .spawn()
453            .expect("spawn isolated group");
454        let pid = child.id();
455        assert!(child.wait().expect("reap child").success());
456        assert!(kill_process_group(pid).is_ok());
457        assert!(kill_process_group_with_signal(pid, KillSignal::Int).is_ok());
458    }
459
460    #[test]
461    fn test_set_parent_death_signal_no_panic() {
462        // Just verify it doesn't panic
463        #[cfg(target_os = "linux")]
464        {
465            let parent_pid = unistd::getpid().as_raw();
466            // Note: This will likely fail in tests since we're not in pre_exec
467            // but it should not panic
468            let _ = set_parent_death_signal(parent_pid);
469        }
470        #[cfg(not(target_os = "linux"))]
471        {
472            assert!(set_parent_death_signal(0).is_ok());
473        }
474    }
475
476    #[test]
477    fn test_kill_nonexistent_process_group() {
478        // Killing a non-existent process group should not error on non-Unix
479        // On Unix, ESRCH (no such process) is converted to Ok() in our implementation
480        #[cfg(unix)]
481        {
482            // Try to kill a very high PID that definitely doesn't exist
483            // Our implementation should return Ok for ESRCH
484            let result = kill_process_group(2_000_000_000);
485            // Just verify it doesn't panic - result depends on kernel
486            let _ = result;
487        }
488        #[cfg(not(unix))]
489        {
490            let result = kill_process_group(999_999);
491            assert!(result.is_ok());
492        }
493    }
494
495    #[test]
496    fn test_kill_signal_values() {
497        // Verify KillSignal enum values
498        assert_ne!(KillSignal::Int, KillSignal::Term);
499        assert_ne!(KillSignal::Term, KillSignal::Kill);
500        assert_ne!(KillSignal::Int, KillSignal::Kill);
501
502        // Test default
503        assert_eq!(KillSignal::default(), KillSignal::Kill);
504    }
505
506    #[test]
507    fn test_graceful_termination_result_debug() {
508        // Verify GracefulTerminationResult can be formatted
509        let results = [
510            GracefulTerminationResult::GracefulExit,
511            GracefulTerminationResult::ForcefulKill,
512            GracefulTerminationResult::AlreadyExited,
513            GracefulTerminationResult::Error,
514        ];
515        for result in &results {
516            let _ = format!("{result:?}");
517        }
518    }
519
520    #[test]
521    fn test_graceful_kill_nonexistent_process() {
522        // Gracefully killing a non-existent PID should return AlreadyExited
523        let result = graceful_kill_process_group_default(2_000_000_000);
524        #[cfg(unix)]
525        {
526            // On Unix, non-existent processes return AlreadyExited
527            assert_eq!(result, GracefulTerminationResult::AlreadyExited);
528        }
529        #[cfg(not(unix))]
530        {
531            // On non-Unix, behavior varies
532            let _ = result;
533        }
534    }
535
536    #[tokio::test]
537    async fn test_graceful_kill_nonexistent_process_async() {
538        let result = graceful_kill_process_group_default_async(2_000_000_000).await;
539        #[cfg(unix)]
540        {
541            assert_eq!(result, GracefulTerminationResult::AlreadyExited);
542        }
543        #[cfg(not(unix))]
544        {
545            let _ = result;
546        }
547    }
548
549    #[cfg(unix)]
550    #[test]
551    fn test_is_process_running_self() {
552        // Our own process should be running
553        let pid = std::process::id();
554        assert!(is_process_running(pid));
555    }
556
557    #[cfg(unix)]
558    #[test]
559    fn test_is_process_running_nonexistent() {
560        // A very high PID should not be running
561        assert!(!is_process_running(2_000_000_000));
562    }
563}