agentmux_common/process.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Best-effort child-process termination, by PID.
5//!
6//! Before this module, the same two operations were implemented five
7//! times across four crates — `agentmux-srv` (twice), `agentmux-cef`,
8//! `agentmux-bashwrap` — one of which described itself as a *"Mirror of
9//! the cef-side helper"* (`docs/reports/REPORT_DRY_AND_MODULARITY_AUDIT_2026_09_06.md`
10//! §2.2). Only one of the five suppressed the console flash that `taskkill`
11//! otherwise causes from a GUI-subsystem parent; here every Windows path
12//! does.
13//!
14//! **This is not `process_tracker`.** That module owns *tracked* agent
15//! process trees (Job Object / cgroup / pgid) and is the right tool when
16//! the child was assigned to a tracker at spawn. These helpers are for the
17//! untracked cases — a one-shot login CLI, a shell node, a pager left
18//! behind by a hook — where all the caller has is a PID.
19//!
20//! Every function is scoped strictly to the given PID (and, on Windows,
21//! its tree via `/T`) — **never** by image name. Killing by image name is
22//! the cross-instance hazard CLAUDE.md bans outright.
23//!
24//! ## The `kill(2)` argument ranges, and why the guards are what they are
25//!
26//! Callers hand us a `u32`; POSIX `kill(2)` takes a signed `pid_t`, and
27//! its argument is **not** simply "a process id". Every range means
28//! something different:
29//!
30//! | `pid` argument | `kill(2)` signals… |
31//! |---|---|
32//! | `> 0` | exactly that one process |
33//! | `== 0` | every process in the **caller's own** process group |
34//! | `== -1` | **every process the caller may signal — a system-wide broadcast** |
35//! | `< -1` | every process in process group `-pid` |
36//!
37//! Three successive ReAgent P1s on PR #3033 each caught this module
38//! hitting one of the non-literal rows through an innocent-looking `u32`:
39//!
40//! 1. `u32::MAX - 1` cast with `as` wraps to `-2` → row four, group 2.
41//! 2. `0` → row two, the caller's own group (the test runner).
42//! 3. `1`, negated for the group call → `-1` → row three, the broadcast.
43//!
44//! So the guards are derived from the table, not added one hole at a time:
45//!
46//! - [`checked_pid`] refuses `0` and anything that does not fit `pid_t`,
47//! which is exactly the set of inputs that could reach rows two and
48//! four from the single-PID path. Every `pid_t` that reaches
49//! [`kill_pid`] is strictly positive → row one only.
50//! - [`signal_process_group`] (and [`kill_process_group`] and
51//! [`force_kill_tree`], which go through it on Unix) additionally
52//! requires `pgid >= 2`, because it negates: `-1` would be row three, and `-0` is `0`, row two. Every
53//! value it passes to `kill(2)` is `<= -2` → row four only, and never
54//! the broadcast.
55//!
56//! Real PIDs are never 0 or 1 for anything this module should touch
57//! (1 is `init`/`systemd`), and never approach `i32::MAX` on any supported
58//! platform (Linux `pid_max` caps at 4194304; Windows PIDs are small
59//! multiples of 4) — so the guards cost nothing in practice and close the
60//! whole class, not just the three instances that were reported.
61
62#[cfg(windows)]
63use crate::win32::NoWindow;
64use std::io;
65
66/// Convert a caller-supplied PID to a signed, **strictly positive** `pid_t`.
67/// Refuses `0` (the caller's own process group to `kill(2)`) and anything
68/// that would wrap negative (a process group, or the broadcast). Shared by
69/// both public functions so the guard can't drift.
70fn checked_pid(pid: u32) -> io::Result<i32> {
71 if pid == 0 {
72 return Err(io::Error::new(
73 io::ErrorKind::InvalidInput,
74 "pid 0 would target the caller's own process group — refusing",
75 ));
76 }
77 i32::try_from(pid).map_err(|_| {
78 io::Error::new(
79 io::ErrorKind::InvalidInput,
80 format!("pid {pid} does not fit in pid_t — refusing (would wrap negative)"),
81 )
82 })
83}
84
85/// Terminate one process by PID — `SIGTERM` on Unix; `taskkill /F /T /PID`
86/// on Windows (which also takes the tree, since Windows has no
87/// process-group signal).
88///
89/// Returns `Err` if the PID is `0` or out of range for `pid_t` (see the
90/// module doc), or if the signal/command could not be delivered. A process
91/// that has already exited surfaces as an error too (Unix `ESRCH`, Windows
92/// non-zero `taskkill` exit) — callers treating "already gone" as success
93/// should ignore the result, which is what every prior copy did.
94///
95/// `1` is accepted here: to `kill(2)` a positive `1` is exactly one process
96/// (row one of the table), not a special value. It only becomes the
97/// broadcast when *negated*, which this function never does.
98pub fn kill_pid(pid: u32) -> io::Result<()> {
99 let pid = checked_pid(pid)?;
100 #[cfg(windows)]
101 {
102 let status = taskkill_tree(pid).status()?;
103 if status.success() {
104 Ok(())
105 } else {
106 Err(io::Error::other(format!("taskkill exit {:?}", status.code())))
107 }
108 }
109 #[cfg(unix)]
110 {
111 // SAFETY: kill(2) is a well-defined POSIX syscall; `pid` is a
112 // checked, strictly-positive pid_t (never 0, never negative), so
113 // this is row one of the module-doc table — exactly one process.
114 let ret = unsafe { libc::kill(pid, libc::SIGTERM) };
115 if ret != 0 {
116 return Err(io::Error::last_os_error());
117 }
118 Ok(())
119 }
120}
121
122/// Terminate a process **group** led by `pid`, with escalation: `SIGTERM`
123/// to the group, a short grace, then `SIGKILL` to the group. On Windows
124/// the same `taskkill /F /T /PID` as [`kill_pid`] — there is no group
125/// signal, and `/T` already takes the tree.
126///
127/// Unix callers must have spawned the child as a group leader
128/// (`process_group(0)` / `setsid`) for the negative-pid signal to reach
129/// its descendants; that is the contract every prior copy relied on.
130/// Best-effort: nothing is returned because there is nothing useful a
131/// caller can do about a failed kill of an already-dying group.
132///
133/// A PID of `0`, `1`, or anything out of range for `pid_t` is a **no-op**.
134/// `0` and out-of-range are refused by [`checked_pid`]; `1` is refused
135/// here specifically because this function negates its argument and
136/// `kill(-1, …)` is the system-wide broadcast (row three of the module-doc
137/// table), not "process group 1".
138pub fn kill_process_group(pid: u32) {
139 let Ok(pgid) = checked_pid(pid) else { return };
140 if pgid < 2 {
141 // pgid == 1 → -pgid == -1 → broadcast to every signalable process.
142 // (pgid == 0 is already impossible here; checked_pid refused it.)
143 return;
144 }
145 #[cfg(windows)]
146 {
147 let _ = taskkill_tree(pgid).status();
148 }
149 #[cfg(unix)]
150 {
151 let _ = signal_process_group(pid, libc::SIGTERM);
152 std::thread::sleep(std::time::Duration::from_millis(300));
153 let _ = signal_process_group(pid, libc::SIGKILL);
154 }
155}
156
157/// Send one `signal` to the process group led by `pid`, with no grace and
158/// no escalation: the building block of [`kill_process_group`], for callers
159/// that pick their own signal and timing (the launcher's teardown backstop).
160/// Same guards: `0`, `1` and anything out of range for `pid_t` are refused
161/// with `InvalidInput` and nothing is sent. An already-empty group is an
162/// `ESRCH` error, which callers usually ignore.
163#[cfg(unix)]
164pub fn signal_process_group(pid: u32, signal: libc::c_int) -> io::Result<()> {
165 let pgid = checked_pid(pid)?;
166 if pgid < 2 {
167 return Err(io::Error::new(
168 io::ErrorKind::InvalidInput,
169 "pgid 1 would be negated to -1, the broadcast to every process — refusing",
170 ));
171 }
172 // SAFETY: kill(2) is a well-defined POSIX syscall; `pgid >= 2` by the
173 // guards above, so `-pgid <= -2`: row four of the module-doc table,
174 // exactly that one process group. It can never be 0 (the caller's own
175 // group) or -1 (the broadcast).
176 if unsafe { libc::kill(-pgid, signal) } != 0 {
177 return Err(io::Error::last_os_error());
178 }
179 Ok(())
180}
181
182/// Kill a process and everything it spawned at once, with no grace:
183/// `SIGKILL` to the process group led by `pid` on Unix (the child must be a
184/// group or session leader), `taskkill /F /T /PID` on Windows. For a caller
185/// that has already asked nicely, or never can (bashwrap's idle kill of a
186/// wrapped command). The guards are [`signal_process_group`]'s on Unix and
187/// [`kill_pid`]'s on Windows; the result is for logging, since "already
188/// gone" is an error too.
189pub fn force_kill_tree(pid: u32) -> io::Result<()> {
190 #[cfg(windows)]
191 {
192 kill_pid(pid)
193 }
194 #[cfg(unix)]
195 {
196 signal_process_group(pid, libc::SIGKILL)
197 }
198}
199
200/// Force-kill a child and, on Unix, the process group it leads: what an
201/// agent CLI spawned with `process_group(0)` needs, since its MCP servers
202/// and other helpers live in that group, not in srv's. Then reap it.
203///
204/// The group is signalled only while tokio hasn't reaped the child
205/// (`id()` is `Some` until then), so the pid, and the group it names, are
206/// still this child's and can't have been reused. A child that doesn't lead
207/// its own group (spawned without `process_group(0)`) gets only the
208/// single-pid kill, as before: its group is srv's.
209pub async fn kill_child_and_group(child: &mut tokio::process::Child) -> io::Result<()> {
210 signal_unreaped_group(child);
211 child.kill().await
212}
213
214/// [`kill_child_and_group`] without the wait, for a caller that reaps the
215/// child later (`start_kill`).
216pub fn start_kill_child_and_group(child: &mut tokio::process::Child) -> io::Result<()> {
217 signal_unreaped_group(child);
218 child.start_kill()
219}
220
221/// A child that, if dropped before it was reaped, takes its process group
222/// with it ([`start_kill_child_and_group`]) rather than only itself, as
223/// `kill_on_drop` does. For a CLI a caller may abandon (a cancelled task):
224/// its helpers live in the CLI's group and would otherwise outlive it. Derefs
225/// to the child.
226pub struct KillGroupOnDrop(pub tokio::process::Child);
227
228impl std::ops::Deref for KillGroupOnDrop {
229 type Target = tokio::process::Child;
230 fn deref(&self) -> &Self::Target {
231 &self.0
232 }
233}
234
235impl std::ops::DerefMut for KillGroupOnDrop {
236 fn deref_mut(&mut self) -> &mut Self::Target {
237 &mut self.0
238 }
239}
240
241impl Drop for KillGroupOnDrop {
242 fn drop(&mut self) {
243 let _ = start_kill_child_and_group(&mut self.0);
244 }
245}
246
247fn signal_unreaped_group(child: &tokio::process::Child) {
248 #[cfg(unix)]
249 if let Some(pid) = child.id() {
250 if leads_own_group(pid) {
251 let _ = signal_process_group(pid, libc::SIGKILL);
252 }
253 }
254 #[cfg(not(unix))]
255 let _ = child;
256}
257
258/// True when `pid` is the leader of its own process group, so `kill(-pid)`
259/// reaches its group and nothing else (never the caller's own group, whose
260/// leader is someone else).
261#[cfg(unix)]
262pub fn leads_own_group(pid: u32) -> bool {
263 let Ok(pid) = checked_pid(pid) else { return false };
264 // SAFETY: getpgid(2) only reads; a pid that isn't running returns -1.
265 pid >= 2 && unsafe { libc::getpgid(pid) } == pid
266}
267
268/// True when process group `pgid` still has members although no process has
269/// that pid any more: its leader exited and was reaped, but what the leader
270/// started (an agent CLI's MCP servers) lives on. The kernel does not hand a
271/// pid out again while it is still a group id, so `kill(-pgid)` reaches
272/// exactly those survivors. `false` while the pid is a live process (the
273/// caller decides then whether it is the same one), and for an empty group.
274#[cfg(unix)]
275pub fn orphaned_group_alive(pgid: u32) -> bool {
276 let Ok(pid) = checked_pid(pgid) else { return false };
277 // SAFETY: signal 0 only checks that the group exists; `pid >= 2` keeps
278 // `-pid` clear of the caller's own group (0) and the broadcast (-1).
279 pid >= 2 && process_start_time(pgid).is_none() && unsafe { libc::kill(-pid, 0) } == 0
280}
281
282/// When `pid` started, in a unit fixed per platform (clock ticks since boot
283/// on Linux, microseconds since the epoch on macOS), or `None` when it isn't
284/// running or the platform can't say. A pid plus its start time names one
285/// process even across pid reuse: the launcher checks both before it
286/// signals a pid it read from a file (`agent_roots`).
287#[cfg(unix)]
288pub fn process_start_time(pid: u32) -> Option<u64> {
289 let pid = checked_pid(pid).ok()?;
290 #[cfg(target_os = "linux")]
291 {
292 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
293 start_time_from_stat(&stat)
294 }
295 #[cfg(target_os = "macos")]
296 {
297 let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
298 let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
299 // SAFETY: proc_pidinfo writes at most `size` bytes into `info`, a
300 // zeroed proc_bsdinfo of exactly that size.
301 let got = unsafe {
302 libc::proc_pidinfo(pid, libc::PROC_PIDTBSDINFO, 0, (&mut info as *mut libc::proc_bsdinfo).cast(), size)
303 };
304 (got == size).then(|| info.pbi_start_tvsec * 1_000_000 + info.pbi_start_tvusec)
305 }
306 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
307 {
308 let _ = pid;
309 None
310 }
311}
312
313/// Field 22 (`starttime`) of a `/proc/<pid>/stat` line. The command name in
314/// field 2 is in parentheses and may itself hold spaces and `)`, so the
315/// fields are counted from the last `)`.
316#[cfg(any(target_os = "linux", test))]
317fn start_time_from_stat(stat: &str) -> Option<u64> {
318 let rest = &stat[stat.rfind(')')? + 1..];
319 // After the `)`: field 3 (state) is the first, so field 22 is the 20th.
320 rest.split_whitespace().nth(19)?.parse().ok()
321}
322
323/// `taskkill /F /T /PID <pid>` with stdio detached and the console flash
324/// suppressed — the one Windows kill command, built once.
325#[cfg(windows)]
326fn taskkill_tree(pid: i32) -> std::process::Command {
327 let mut cmd = std::process::Command::new("taskkill");
328 cmd.args(["/F", "/T", "/PID", &pid.to_string()])
329 .stdin(std::process::Stdio::null())
330 .stdout(std::process::Stdio::null())
331 .stderr(std::process::Stdio::null())
332 .no_window();
333 cmd
334}
335
336/// The cap on srv's app-exit teardown (`agent_teardown::app_exit`: every
337/// agent closed, then leftover shells swept). Shared so the launcher's wait
338/// for srv ([`SRV_EXIT_WAIT`]) stays above it.
339pub const SRV_APP_EXIT_CAP: std::time::Duration = std::time::Duration::from_secs(8);
340
341/// How long the launcher waits for srv to exit on its own after telling it
342/// to (stdin closed; on Unix also SIGTERM) before force-killing it: on every
343/// quit and on an upgrade (`upgrade::quiesce_srv`). Above
344/// [`SRV_APP_EXIT_CAP`] with room for srv's own exit, so a force-kill never
345/// lands mid-teardown. srv usually exits well before it.
346pub const SRV_EXIT_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
347const _: () = assert!(SRV_EXIT_WAIT.as_millis() > SRV_APP_EXIT_CAP.as_millis() + 1000);
348
349/// The exit code of the CEF host when it stops at start-up because the browser sandbox is blocked by system
350/// policy (AppArmor) and the start was made from an agent's environment, where nobody can answer the dialog
351/// (`agentmux_cef::linux_sandbox`). `78` is `EX_CONFIG`. The launcher does not relaunch the host on it (a relaunch
352/// would stop the same way, three times) and exits with it, so a `task dev` run ends with this code within seconds.
353pub const HOST_EXIT_SANDBOX_UNAVAILABLE: i32 = 78;
354
355#[cfg(test)]
356mod tests {
357 use super::*;
358
359 // ── Row two: pid 0 is the caller's own group ────────────────────────
360
361 #[test]
362 fn kill_pid_refuses_zero() {
363 let err = kill_pid(0).unwrap_err();
364 assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{err}");
365 assert!(err.to_string().contains("own process group"), "{err}");
366 }
367
368 #[test]
369 fn kill_process_group_refuses_zero() {
370 kill_process_group(0);
371 }
372
373 // ── Row three: pgid 1 negated is -1, the broadcast ──────────────────
374
375 /// The third P1: `kill_process_group(1)` would have called
376 /// `kill(-1, SIGTERM)` then `kill(-1, SIGKILL)` — every process the
377 /// runner may signal. Must be a silent no-op, reached without any
378 /// syscall.
379 #[test]
380 fn kill_process_group_refuses_one() {
381 kill_process_group(1);
382 }
383
384 // ── Row four via overflow: u32::MAX - 1 wraps to -2 ─────────────────
385
386 #[test]
387 fn kill_pid_refuses_a_pid_that_would_wrap_negative() {
388 let err = kill_pid(u32::MAX - 1).unwrap_err();
389 assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{err}");
390 assert!(err.to_string().contains("does not fit"), "{err}");
391 }
392
393 #[test]
394 fn kill_process_group_refuses_a_pid_that_would_wrap_negative() {
395 kill_process_group(u32::MAX - 1);
396 }
397
398 // ── Row one: a real, positive, nonexistent pid fails cleanly ────────
399
400 /// `i32::MAX` fits `pid_t`, so the guard must pass it through — and it
401 /// cannot be a live process on any supported platform, so the OS
402 /// rejects it (`ESRCH` / non-zero `taskkill`). Asserting the error is
403 /// NOT the guard's proves the syscall was actually made.
404 #[test]
405 fn kill_pid_on_a_nonexistent_in_range_pid_is_an_error_not_a_panic() {
406 let err = kill_pid(i32::MAX as u32).unwrap_err();
407 assert_ne!(err.kind(), io::ErrorKind::InvalidInput, "guard should NOT have fired: {err}");
408 }
409
410 /// The guard's exact contract: strictly positive and fits `pid_t`.
411 /// `1` passes `checked_pid` — it is a legitimate single-process target
412 /// for `kill_pid`; only `kill_process_group` layers the `>= 2` rule on
413 /// top, because only it negates.
414 #[test]
415 fn checked_pid_boundaries() {
416 assert!(checked_pid(0).is_err(), "0 is the caller's own group");
417 assert_eq!(checked_pid(1).unwrap(), 1);
418 assert_eq!(checked_pid(i32::MAX as u32).unwrap(), i32::MAX);
419 assert!(checked_pid(i32::MAX as u32 + 1).is_err());
420 assert!(checked_pid(u32::MAX).is_err());
421 }
422
423 // ── signal_process_group / force_kill_tree: the same guards ──────────
424
425 #[test]
426 fn force_kill_tree_refuses_zero_and_a_pid_that_would_wrap_negative() {
427 for pid in [0, u32::MAX - 1] {
428 let err = force_kill_tree(pid).unwrap_err();
429 assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{pid}: {err}");
430 }
431 }
432
433 #[cfg(unix)]
434 #[test]
435 fn signal_process_group_refuses_zero_one_and_overflow() {
436 for pid in [0, 1, u32::MAX - 1] {
437 let err = signal_process_group(pid, 0).unwrap_err();
438 assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{pid}: {err}");
439 }
440 }
441
442 /// What bashwrap's idle kill relies on: one SIGKILL to the group of a
443 /// child spawned as its own group leader, with no grace period.
444 #[cfg(unix)]
445 #[test]
446 fn force_kill_tree_sigkills_the_group() {
447 use std::os::unix::process::{CommandExt as _, ExitStatusExt as _};
448 let mut child = std::process::Command::new("sleep")
449 .arg("30")
450 .process_group(0)
451 .spawn()
452 .expect("spawn sleep");
453 force_kill_tree(child.id()).expect("signal the group");
454 let status = child.wait().expect("reap sleep");
455 assert_eq!(status.signal(), Some(libc::SIGKILL));
456 }
457
458 #[test]
459 fn start_time_is_field_22_even_with_a_paren_in_the_name() {
460 let stat = "4242 (a) b (c) S 1 4242 4242 0 -1 4194560 100 0 0 0 1 2 0 0 20 0 1 0 987654 1000 10";
461 assert_eq!(start_time_from_stat(stat), Some(987654));
462 assert_eq!(start_time_from_stat("4242 (x) S 1"), None);
463 }
464
465 #[cfg(unix)]
466 #[test]
467 fn a_running_process_has_a_start_time_and_a_gone_one_has_none() {
468 let mut child = std::process::Command::new("sleep").arg("30").spawn().expect("spawn sleep");
469 let start = process_start_time(child.id());
470 assert!(start.is_some());
471 assert_eq!(process_start_time(child.id()), start, "stable while it runs");
472 child.kill().unwrap();
473 child.wait().unwrap();
474 assert_eq!(process_start_time(child.id()), None);
475 assert_eq!(process_start_time(0), None);
476 }
477
478 /// An agent CLI's teardown: the CLI leads its own group, so the kill
479 /// takes what it started too (here a grandchild `sleep`), and leaves the
480 /// caller's group alone.
481 #[cfg(unix)]
482 #[tokio::test]
483 async fn kill_child_and_group_takes_the_grandchild() {
484 let mut cmd = tokio::process::Command::new("sh");
485 cmd.args(["-c", "sleep 30 & echo $!; wait"]).stdout(std::process::Stdio::piped()).process_group(0);
486 let mut child = cmd.spawn().expect("spawn sh");
487 let pid = child.id().unwrap();
488 assert!(leads_own_group(pid));
489 let mut out = child.stdout.take().unwrap();
490 let mut line = Vec::new();
491 let mut byte = [0u8; 1];
492 while tokio::io::AsyncReadExt::read(&mut out, &mut byte).await.unwrap() == 1 && byte[0] != b'\n' {
493 line.push(byte[0]);
494 }
495 let grandchild: u32 = String::from_utf8(line).unwrap().trim().parse().unwrap();
496 assert!(process_start_time(grandchild).is_some());
497 kill_child_and_group(&mut child).await.unwrap();
498 let mut gone = false;
499 for _ in 0..50 {
500 // The grandchild is reparented and reaped by init once killed.
501 if process_start_time(grandchild).is_none() || is_zombie(grandchild) {
502 gone = true;
503 break;
504 }
505 std::thread::sleep(std::time::Duration::from_millis(20));
506 }
507 assert!(gone, "the grandchild in the CLI's group was killed");
508 }
509
510 #[cfg(unix)]
511 fn is_zombie(pid: u32) -> bool {
512 #[cfg(target_os = "linux")]
513 {
514 std::fs::read_to_string(format!("/proc/{pid}/stat"))
515 .ok()
516 .and_then(|s| s.rfind(')').map(|i| s[i + 1..].trim_start().starts_with('Z')))
517 .unwrap_or(false)
518 }
519 #[cfg(not(target_os = "linux"))]
520 {
521 let _ = pid;
522 false
523 }
524 }
525
526 /// One agent's teardown leaves another agent's CLI and helpers alone.
527 #[cfg(unix)]
528 #[tokio::test]
529 async fn kill_child_and_group_leaves_a_sibling_group_alone() {
530 let spawn = || {
531 let mut cmd = tokio::process::Command::new("sh");
532 cmd.args(["-c", "sleep 30 & wait"]).process_group(0);
533 cmd.spawn().expect("spawn sh")
534 };
535 let mut one = spawn();
536 let mut other = spawn();
537 kill_child_and_group(&mut one).await.unwrap();
538 let other_pid = other.id().unwrap();
539 assert!(leads_own_group(other_pid), "the sibling's group still has its leader");
540 assert!(other.try_wait().unwrap().is_none(), "the sibling still runs");
541 kill_child_and_group(&mut other).await.unwrap();
542 }
543
544 /// A leader that exited and was reaped leaves a group the kernel still
545 /// holds: it is reported alive until its last member is gone.
546 #[cfg(unix)]
547 #[test]
548 fn a_group_outlives_its_reaped_leader_until_its_last_member_exits() {
549 use std::io::BufRead as _;
550 use std::os::unix::process::CommandExt as _;
551 let mut leader = std::process::Command::new("sh")
552 .args(["-c", "sleep 30 & echo $!"])
553 .stdout(std::process::Stdio::piped())
554 .process_group(0)
555 .spawn()
556 .unwrap();
557 let pgid = leader.id();
558 let mut line = String::new();
559 std::io::BufReader::new(leader.stdout.take().unwrap()).read_line(&mut line).unwrap();
560 let helper: i32 = line.trim().parse().unwrap();
561 leader.wait().unwrap();
562 assert!(orphaned_group_alive(pgid), "the helper still holds the group");
563 assert!(!orphaned_group_alive(0) && !orphaned_group_alive(1));
564 // SAFETY: the helper is the sleep started above.
565 unsafe { libc::kill(helper, libc::SIGKILL) };
566 for _ in 0..100 {
567 if !orphaned_group_alive(pgid) {
568 return;
569 }
570 std::thread::sleep(std::time::Duration::from_millis(20));
571 }
572 panic!("the group is still reported alive after its last member was killed");
573 }
574
575 /// An abandoned CLI (its task dropped) takes its helpers with it.
576 #[cfg(unix)]
577 #[tokio::test]
578 async fn a_dropped_guard_kills_the_childs_group() {
579 let mut cmd = tokio::process::Command::new("sh");
580 cmd.args(["-c", "sleep 30 & echo $!; wait"]).stdout(std::process::Stdio::piped()).process_group(0);
581 let mut guard = KillGroupOnDrop(cmd.spawn().expect("spawn sh"));
582 let mut out = guard.stdout.take().unwrap();
583 let mut line = Vec::new();
584 let mut byte = [0u8; 1];
585 while tokio::io::AsyncReadExt::read(&mut out, &mut byte).await.unwrap() == 1 && byte[0] != b'\n' {
586 line.push(byte[0]);
587 }
588 let helper: u32 = String::from_utf8(line).unwrap().trim().parse().unwrap();
589 assert!(process_start_time(helper).is_some());
590 drop(guard);
591 let mut gone = false;
592 for _ in 0..100 {
593 if process_start_time(helper).is_none() || is_zombie(helper) {
594 gone = true;
595 break;
596 }
597 std::thread::sleep(std::time::Duration::from_millis(20));
598 }
599 assert!(gone, "the helper outlived the dropped guard");
600 }
601
602 /// A child that doesn't lead its own group is killed by pid alone: its
603 /// group is the caller's.
604 #[cfg(unix)]
605 #[tokio::test]
606 async fn a_child_in_the_callers_group_is_killed_alone() {
607 let mut child = tokio::process::Command::new("sleep").arg("30").spawn().expect("spawn sleep");
608 assert!(!leads_own_group(child.id().unwrap()));
609 kill_child_and_group(&mut child).await.unwrap();
610 assert!(child.wait().await.is_ok());
611 }
612
613 #[cfg(windows)]
614 #[test]
615 fn taskkill_command_targets_pid_never_image_name() {
616 let cmd = taskkill_tree(4242);
617 let args: Vec<String> = cmd.get_args().map(|a| a.to_string_lossy().into_owned()).collect();
618 assert_eq!(args, ["/F", "/T", "/PID", "4242"]);
619 assert!(!args.iter().any(|a| a.eq_ignore_ascii_case("/IM")));
620 }
621}