Skip to main content

sysprims_signal/
lib.rs

1//! sysprims-signal: Cross-platform signal dispatch.
2//!
3//! This crate provides:
4//! - Process signal dispatch by PID ([`kill`])
5//! - Process group signal dispatch by PGID ([`killpg`], Unix-only)
6//! - Convenience wrappers ([`terminate`], [`force_kill`], etc.)
7//!
8//! Errors use the canonical [`sysprims_core::SysprimsError`] type.
9//!
10//! # Safety
11//!
12//! This crate validates PIDs to prevent dangerous POSIX signal semantics:
13//!
14//! - **PID 0 rejected**: `kill(0, sig)` would signal the caller's process group
15//! - **PID > i32::MAX rejected**: Large u32 values wrap to negative i32, and
16//!   `kill(-1, sig)` signals ALL processes the caller can reach
17//!
18//! See `docs/safety/signal-dispatch.md` for full details on POSIX signal
19//! semantics and why these restrictions exist.
20
21use sysprims_core::{SysprimsError, SysprimsResult};
22
23/// Maximum valid PID value.
24///
25/// PIDs above this value would overflow to negative when cast to `pid_t` (i32),
26/// which has special POSIX semantics:
27/// - `kill(-1, sig)` = signal ALL processes the caller can reach
28/// - `kill(-pgid, sig)` = signal process group `pgid`
29///
30/// We reject these at the API boundary to prevent accidental mass termination.
31pub const MAX_SAFE_PID: u32 = i32::MAX as u32;
32
33pub(crate) const TERMINATE_SIGNAL: i32 = SIGTERM;
34pub(crate) const FORCE_KILL_SIGNAL: i32 = SIGKILL;
35
36pub mod handle;
37pub use handle::{
38    open_process_handle, open_process_handle_verified, with_forced_checked_numeric_for_test,
39    ProcessHandle, SignalBinding,
40};
41
42/// Validate that a parameter (`pid` or `pgid`) is safe to use with POSIX signal functions.
43///
44/// Returns an error if:
45/// - `pid == 0`: Would signal the caller's process group
46/// - `pid > i32::MAX`: Would overflow to negative, triggering broadcast semantics
47fn validate_pid_param(pid: u32, param_name: &str) -> SysprimsResult<()> {
48    if pid == 0 {
49        return Err(SysprimsError::invalid_argument(format!(
50            "{param_name} must be > 0"
51        )));
52    }
53    if pid > MAX_SAFE_PID {
54        return Err(SysprimsError::invalid_argument(format!(
55            "{param_name} {} exceeds maximum safe value {}; \
56             larger values overflow to negative PIDs with dangerous POSIX semantics \
57             (see docs/safety/signal-dispatch.md)",
58            pid, MAX_SAFE_PID
59        )));
60    }
61    Ok(())
62}
63
64/// Validate that a PID is safe (`1..=MAX_SAFE_PID`) per ADR-0011.
65pub fn validate_pid(pid: u32) -> SysprimsResult<()> {
66    validate_pid_param(pid, "pid")
67}
68
69/// Validate that a PGID is safe (`1..=MAX_SAFE_PID`) per ADR-0011.
70pub fn validate_pgid(pgid: u32) -> SysprimsResult<()> {
71    validate_pid_param(pgid, "pgid")
72}
73
74#[derive(Debug)]
75pub struct BatchKillFailure {
76    pub pid: u32,
77    pub error: SysprimsError,
78}
79
80#[derive(Debug, Default)]
81pub struct BatchKillResult {
82    pub succeeded: Vec<u32>,
83    pub failed: Vec<BatchKillFailure>,
84}
85
86fn validate_pid_list(pids: &[u32], param_name: &str) -> SysprimsResult<()> {
87    if pids.is_empty() {
88        return Err(SysprimsError::invalid_argument(format!(
89            "{param_name} must not be empty"
90        )));
91    }
92
93    for &pid in pids {
94        validate_pid_param(pid, param_name)?;
95    }
96
97    Ok(())
98}
99
100#[cfg(unix)]
101mod unix;
102#[cfg(windows)]
103mod windows;
104
105// Re-export rsfulmen signal constants and helpers for convenience.
106//
107// This crate is explicitly about signals, so re-exporting these at the crate
108// root is intentional and ergonomic.
109pub use rsfulmen::foundry::signals::*;
110
111/// User-defined signal 1 (`30` on macOS, `10` on Linux and other platforms).
112#[cfg(target_os = "macos")]
113pub const SIGUSR1: i32 = 30;
114/// User-defined signal 1 (`30` on macOS, `10` on Linux and other platforms).
115#[cfg(not(target_os = "macos"))]
116pub const SIGUSR1: i32 = 10;
117
118/// User-defined signal 2 (`31` on macOS, `12` on Linux and other platforms).
119#[cfg(target_os = "macos")]
120pub const SIGUSR2: i32 = 31;
121/// User-defined signal 2 (`31` on macOS, `12` on Linux and other platforms).
122#[cfg(not(target_os = "macos"))]
123pub const SIGUSR2: i32 = 12;
124
125fn resolve_signal_number(signal_name: &str) -> Option<i32> {
126    let trimmed = signal_name.trim();
127    if trimmed.is_empty() {
128        return None;
129    }
130
131    if let Some(num) = get_signal_number(trimmed) {
132        return Some(num);
133    }
134
135    let upper = trimmed.to_ascii_uppercase();
136    if let Some(num) = get_signal_number(&upper) {
137        return Some(num);
138    }
139
140    if !upper.starts_with("SIG") {
141        let with_sig = format!("SIG{upper}");
142        if let Some(num) = get_signal_number(&with_sig) {
143            return Some(num);
144        }
145    }
146
147    let lower = trimmed.to_ascii_lowercase();
148    lookup_signal_by_id(&lower).and_then(|signal| get_signal_number(&signal.name))
149}
150
151fn glob_match(pattern: &str, text: &str) -> bool {
152    let pattern = pattern.as_bytes();
153    let text = text.as_bytes();
154    let mut p_idx = 0;
155    let mut t_idx = 0;
156    let mut star_idx: Option<usize> = None;
157    let mut match_idx = 0;
158
159    while t_idx < text.len() {
160        if p_idx < pattern.len() && (pattern[p_idx] == b'?' || pattern[p_idx] == text[t_idx]) {
161            p_idx += 1;
162            t_idx += 1;
163            continue;
164        }
165        if p_idx < pattern.len() && pattern[p_idx] == b'*' {
166            star_idx = Some(p_idx);
167            match_idx = t_idx;
168            p_idx += 1;
169            continue;
170        }
171        if let Some(star) = star_idx {
172            p_idx = star + 1;
173            match_idx += 1;
174            t_idx = match_idx;
175            continue;
176        }
177        return false;
178    }
179
180    while p_idx < pattern.len() && pattern[p_idx] == b'*' {
181        p_idx += 1;
182    }
183
184    p_idx == pattern.len()
185}
186
187/// Send a signal to a process.
188///
189/// # Errors
190///
191/// Returns [`SysprimsError::InvalidArgument`] if:
192/// - `pid == 0`: Would signal the caller's process group (use [`killpg`] explicitly)
193/// - `pid > MAX_SAFE_PID`: Would overflow to negative, triggering POSIX broadcast
194///
195/// See [ADR-0011](https://github.com/3leaps/sysprims/blob/main/docs/decisions/ADR-0011-pid-validation-safety.md)
196/// for rationale.
197/// Prefer this over shelling out to `kill -TERM <pid>` and parsing command failures.
198///
199/// # Examples
200///
201/// ```rust,no_run
202/// use sysprims_signal::SIGTERM;
203///
204/// // Replaces: kill -TERM 4242
205/// sysprims_signal::kill(4242, SIGTERM).ok();
206/// ```
207pub fn kill(pid: u32, signal: i32) -> SysprimsResult<()> {
208    validate_pid(pid)?;
209
210    #[cfg(unix)]
211    return unix::kill_impl(pid, signal);
212
213    #[cfg(windows)]
214    return windows::kill_impl(pid, signal);
215}
216
217/// Send a signal to multiple processes.
218///
219/// PID validation happens for the entire slice before any signals are sent.
220/// Individual send failures are collected and returned in the aggregate result.
221///
222/// # Errors
223///
224/// Returns [`SysprimsError::InvalidArgument`] if:
225/// - `pids` is empty
226/// - any PID in `pids` is invalid (e.g. 0 or > [`MAX_SAFE_PID`])
227///
228/// # Examples
229///
230/// ```rust,no_run
231/// use sysprims_signal::SIGTERM;
232///
233/// // Replaces: kill -TERM 1234 && kill -TERM 5678
234/// let result = sysprims_signal::kill_many(&[1234, 5678], SIGTERM).unwrap();
235/// println!("sent to {}", result.succeeded.len());
236/// ```
237pub fn kill_many(pids: &[u32], signal: i32) -> SysprimsResult<BatchKillResult> {
238    validate_pid_list(pids, "pids")?;
239
240    let mut result = BatchKillResult::default();
241    for &pid in pids {
242        match kill(pid, signal) {
243            Ok(()) => result.succeeded.push(pid),
244            Err(error) => result.failed.push(BatchKillFailure { pid, error }),
245        }
246    }
247
248    Ok(result)
249}
250
251/// Convenience wrapper: send `SIGTERM` to multiple processes.
252///
253/// # Examples
254///
255/// ```rust,no_run
256/// // Replaces: xargs -n1 kill -TERM
257/// let _ = sysprims_signal::terminate_many(&[1234, 5678]);
258/// ```
259pub fn terminate_many(pids: &[u32]) -> SysprimsResult<BatchKillResult> {
260    kill_many(pids, SIGTERM)
261}
262
263/// Convenience wrapper: send `SIGKILL` to multiple processes.
264///
265/// # Examples
266///
267/// ```rust,no_run
268/// // Replaces: xargs -n1 kill -KILL
269/// let _ = sysprims_signal::force_kill_many(&[1234, 5678]);
270/// ```
271pub fn force_kill_many(pids: &[u32]) -> SysprimsResult<BatchKillResult> {
272    kill_many(pids, SIGKILL)
273}
274
275/// Resolve a signal number by name (`SIGTERM`, `TERM`, `sigterm`, or short ID `term`).
276pub fn resolve_signal_name(signal_name: &str) -> SysprimsResult<i32> {
277    resolve_signal_number(signal_name).ok_or_else(|| {
278        SysprimsError::invalid_argument(format!("unknown signal name: {signal_name}"))
279    })
280}
281
282/// Send a signal to a process, resolving the signal number by name.
283///
284/// This uses rsfulmen's catalog plus a small normalization layer:
285/// - Accepts `SIGTERM`, `TERM`, or `sigterm`
286/// - Accepts short IDs like `term` or `int`
287///
288/// # Examples
289///
290/// ```rust,no_run
291/// // Replaces: kill -TERM 1234
292/// sysprims_signal::kill_by_name(1234, "TERM").ok();
293/// ```
294pub fn kill_by_name(pid: u32, signal_name: &str) -> SysprimsResult<()> {
295    let signal = resolve_signal_name(signal_name)?;
296    kill(pid, signal)
297}
298
299/// Send a signal to a process group, resolving the signal number by name.
300pub fn kill_group_by_name(pgid: u32, signal_name: &str) -> SysprimsResult<()> {
301    let signal = resolve_signal_name(signal_name)?;
302    killpg(pgid, signal)
303}
304
305/// Send a signal to a process group.
306///
307/// On Windows, this always returns `NotSupported`.
308///
309/// # Errors
310///
311/// Returns [`SysprimsError::InvalidArgument`] if:
312/// - `pgid == 0`: Would signal the caller's process group
313/// - `pgid > MAX_SAFE_PID`: Would overflow to negative
314///
315/// See [ADR-0011](https://github.com/3leaps/sysprims/blob/main/docs/decisions/ADR-0011-pid-validation-safety.md)
316/// for rationale.
317///
318/// # Examples
319///
320/// ```rust,no_run
321/// use sysprims_signal::SIGTERM;
322///
323/// // Replaces: kill -TERM -- -4242
324/// sysprims_signal::killpg(4242, SIGTERM).ok();
325/// ```
326pub fn killpg(pgid: u32, signal: i32) -> SysprimsResult<()> {
327    validate_pgid(pgid)?;
328
329    #[cfg(unix)]
330    return unix::killpg_impl(pgid, signal);
331
332    #[cfg(windows)]
333    {
334        let _ = signal; // Unused on Windows
335        return Err(SysprimsError::not_supported("killpg", "windows"));
336    }
337}
338
339/// Return signal names that match a simple glob pattern.
340///
341/// Supports `*` (any sequence) and `?` (single char). Matching is
342/// ASCII case-insensitive and checks both the signal name and short ID.
343///
344/// # Examples
345///
346/// ```rust
347/// // Replaces: kill -l | grep -i term
348/// let matches = sysprims_signal::match_signal_names("*term*");
349/// assert!(matches.iter().any(|name| *name == "SIGTERM"));
350/// ```
351pub fn match_signal_names(pattern: &str) -> Vec<&'static str> {
352    let trimmed = pattern.trim();
353    if trimmed.is_empty() {
354        return Vec::new();
355    }
356
357    let pattern = trimmed.to_ascii_lowercase();
358    let mut matches = Vec::new();
359
360    for signal in list_signals() {
361        let name = signal.name.to_ascii_lowercase();
362        let id = signal.id.to_ascii_lowercase();
363        if (glob_match(&pattern, &name) || glob_match(&pattern, &id))
364            && !matches.iter().any(|&item| item == signal.name)
365        {
366            matches.push(signal.name.as_str());
367        }
368    }
369
370    matches
371}
372
373/// Convenience wrapper: send `SIGTERM` (or Windows terminate).
374///
375/// # Examples
376///
377/// ```rust,no_run
378/// // Replaces: kill -TERM 1234
379/// sysprims_signal::terminate(1234).ok();
380/// ```
381pub fn terminate(pid: u32) -> SysprimsResult<()> {
382    kill(pid, SIGTERM)
383}
384
385/// Convenience wrapper: send `SIGKILL` (or Windows terminate).
386///
387/// # Examples
388///
389/// ```rust,no_run
390/// // Replaces: kill -KILL 1234
391/// sysprims_signal::force_kill(1234).ok();
392/// ```
393pub fn force_kill(pid: u32) -> SysprimsResult<()> {
394    kill(pid, SIGKILL)
395}
396
397/// Convenience wrapper: send `SIGTERM` to a process group.
398///
399/// # Examples
400///
401/// ```rust,no_run
402/// // Replaces: kill -TERM -- -4242
403/// sysprims_signal::terminate_group(4242).ok();
404/// ```
405pub fn terminate_group(pgid: u32) -> SysprimsResult<()> {
406    killpg(pgid, SIGTERM)
407}
408
409/// Convenience wrapper: send `SIGKILL` to a process group.
410///
411/// # Examples
412///
413/// ```rust,no_run
414/// // Replaces: kill -KILL -- -4242
415/// sysprims_signal::force_kill_group(4242).ok();
416/// ```
417pub fn force_kill_group(pgid: u32) -> SysprimsResult<()> {
418    killpg(pgid, SIGKILL)
419}
420
421#[cfg(test)]
422mod tests {
423    use super::*;
424
425    // ========================================================================
426    // PID Validation Tests (ADR-0011)
427    // ========================================================================
428
429    #[test]
430    fn kill_rejects_pid_zero() {
431        let err = kill(0, SIGTERM).unwrap_err();
432        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
433        assert!(err.to_string().contains("must be > 0"));
434    }
435
436    #[test]
437    fn killpg_rejects_pgid_zero() {
438        let err = killpg(0, SIGTERM).unwrap_err();
439        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
440        assert!(err.to_string().contains("must be > 0"));
441    }
442
443    #[test]
444    fn kill_rejects_pid_exceeding_max_safe() {
445        // This is the critical safety test per ADR-0011.
446        //
447        // u32::MAX (4294967295) cast to i32 becomes -1.
448        // kill(-1, sig) is POSIX for "signal ALL processes you can reach".
449        // This would terminate Finder, Terminal, and everything else!
450        let err = kill(u32::MAX, SIGTERM).unwrap_err();
451        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
452        assert!(err.to_string().contains("exceeds maximum safe value"));
453    }
454
455    #[test]
456    fn killpg_rejects_pgid_exceeding_max_safe() {
457        let err = killpg(u32::MAX, SIGTERM).unwrap_err();
458        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
459        assert!(err.to_string().contains("exceeds maximum safe value"));
460    }
461
462    #[test]
463    fn kill_rejects_pid_at_boundary() {
464        // i32::MAX + 1 is the first unsafe value
465        let first_unsafe = (i32::MAX as u32) + 1;
466        let err = kill(first_unsafe, SIGTERM).unwrap_err();
467        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
468    }
469
470    #[test]
471    fn kill_accepts_pid_at_max_safe() {
472        // i32::MAX is the last safe value (will return NotFound, not validation error)
473        let result = kill(MAX_SAFE_PID, SIGTERM);
474        // Should NOT be InvalidArgument - should be NotFound or PermissionDenied
475        assert!(!matches!(
476            result,
477            Err(SysprimsError::InvalidArgument { .. })
478        ));
479    }
480
481    #[test]
482    fn max_safe_pid_is_i32_max() {
483        assert_eq!(MAX_SAFE_PID, i32::MAX as u32);
484        assert_eq!(MAX_SAFE_PID, 2147483647);
485    }
486
487    #[test]
488    fn kill_many_rejects_empty_pid_list() {
489        let err = kill_many(&[], SIGTERM).unwrap_err();
490        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
491        assert!(err.to_string().contains("must not be empty"));
492    }
493
494    // ========================================================================
495    // rsfulmen Integration Tests
496    // ========================================================================
497
498    #[test]
499    fn rsfulmen_constants_available() {
500        assert_eq!(SIGTERM, 15);
501        assert_eq!(SIGKILL, 9);
502    }
503
504    // ========================================================================
505    // Signal Name Resolution Tests
506    // ========================================================================
507
508    #[test]
509    fn resolve_signal_number_accepts_common_variants() {
510        assert_eq!(resolve_signal_number("SIGTERM"), Some(SIGTERM));
511        assert_eq!(resolve_signal_number("term"), Some(SIGTERM));
512        assert_eq!(resolve_signal_number("TERM"), Some(SIGTERM));
513        assert_eq!(resolve_signal_number(" sigterm "), Some(SIGTERM));
514    }
515
516    #[test]
517    fn resolve_signal_number_accepts_short_id() {
518        assert_eq!(resolve_signal_number("int"), Some(SIGINT));
519    }
520
521    #[test]
522    fn match_signal_names_glob_matches_names() {
523        let matches = match_signal_names("SIGT*");
524        assert!(matches.contains(&"SIGTERM"));
525    }
526
527    // ========================================================================
528    // Platform-Specific Tests
529    // ========================================================================
530
531    #[test]
532    #[cfg(windows)]
533    fn killpg_is_not_supported_on_windows() {
534        let err = killpg(1234, SIGTERM).unwrap_err();
535        assert!(matches!(err, SysprimsError::NotSupported { .. }));
536    }
537
538    // ========================================================================
539    // ProcessHandle Tests
540    // ========================================================================
541
542    fn spawn_sleep_child() -> std::process::Child {
543        #[cfg(unix)]
544        {
545            std::process::Command::new("sleep")
546                .arg("30")
547                .stdin(std::process::Stdio::null())
548                .stdout(std::process::Stdio::null())
549                .stderr(std::process::Stdio::null())
550                .spawn()
551                .expect("spawn sleep child")
552        }
553        #[cfg(windows)]
554        {
555            std::process::Command::new("ping")
556                .args(["-n", "30", "127.0.0.1"])
557                .stdin(std::process::Stdio::null())
558                .stdout(std::process::Stdio::null())
559                .stderr(std::process::Stdio::null())
560                .spawn()
561                .expect("spawn ping child")
562        }
563    }
564
565    #[test]
566    fn process_handle_rejects_invalid_pids() {
567        let err_zero = open_process_handle(0).unwrap_err();
568        assert!(matches!(err_zero, SysprimsError::InvalidArgument { .. }));
569
570        let err_max = open_process_handle(u32::MAX).unwrap_err();
571        assert!(matches!(err_max, SysprimsError::InvalidArgument { .. }));
572
573        let err_boundary = open_process_handle(MAX_SAFE_PID + 1).unwrap_err();
574        assert!(matches!(
575            err_boundary,
576            SysprimsError::InvalidArgument { .. }
577        ));
578    }
579
580    #[test]
581    fn process_handle_verified_rejects_empty_and_mismatched_start_identity() {
582        let self_pid = std::process::id();
583        let err_empty = open_process_handle_verified(self_pid, "   ").unwrap_err();
584        assert!(matches!(err_empty, SysprimsError::InvalidArgument { .. }));
585
586        let handle = open_process_handle(self_pid).expect("open self handle");
587        assert_eq!(handle.pid(), self_pid);
588        assert!(!handle.start_identity().is_empty());
589
590        let verified = open_process_handle_verified(self_pid, handle.start_identity())
591            .expect("open verified self handle");
592        assert_eq!(verified.start_identity(), handle.start_identity());
593
594        let err_mismatch = open_process_handle_verified(self_pid, "0000000000.999999").unwrap_err();
595        assert!(matches!(err_mismatch, SysprimsError::NotFound { .. }));
596    }
597
598    #[test]
599    fn process_handle_lifecycle_and_latched_exit() {
600        let mut child = spawn_sleep_child();
601        let pid = child.id();
602
603        let handle = open_process_handle(pid).expect("open child handle");
604        assert_eq!(handle.pid(), pid);
605        assert!(!handle.start_identity().is_empty());
606        assert!(!handle.exited().expect("exited check on live child"));
607
608        #[cfg(target_os = "macos")]
609        assert_eq!(handle.binding(), SignalBinding::CheckedNumeric);
610        #[cfg(any(target_os = "linux", target_os = "windows"))]
611        assert_eq!(handle.binding(), SignalBinding::Bound);
612
613        let binding = handle.force_kill().expect("force_kill bound child");
614        assert_eq!(binding, handle.binding());
615
616        let _ = child.wait();
617
618        // Wait briefly for OS exit observation if needed, then verify latched true.
619        let mut observed_exit = false;
620        for _ in 0..50 {
621            if handle.exited().expect("exited check after wait") {
622                observed_exit = true;
623                break;
624            }
625            std::thread::sleep(std::time::Duration::from_millis(10));
626        }
627        assert!(
628            observed_exit,
629            "expected exited() to become true after child exit"
630        );
631        assert!(handle.exited().expect("latched exited check"));
632
633        // Second signal after exit must refuse with NotFound without signaling numeric PID.
634        let second = handle.force_kill().unwrap_err();
635        assert!(matches!(second, SysprimsError::NotFound { .. }));
636
637        // Opening a new handle on the reaped PID (or with the old start_identity) must fail.
638        let reopen = open_process_handle_verified(pid, handle.start_identity()).unwrap_err();
639        assert!(matches!(reopen, SysprimsError::NotFound { .. }));
640
641        handle.close();
642        assert!(handle.is_closed());
643        handle.close(); // idempotent
644        let err_closed = handle.exited().unwrap_err();
645        assert!(matches!(err_closed, SysprimsError::InvalidArgument { .. }));
646    }
647
648    #[test]
649    fn process_handle_detects_unreaped_zombie_exit_and_refuses_signal() {
650        let mut child = spawn_sleep_child();
651        let pid = child.id();
652        let handle = open_process_handle(pid).expect("open child handle");
653
654        let _ = child.kill();
655        // Deliberately do NOT wait() yet so child becomes an unreaped zombie on Unix.
656        let mut observed_exit = false;
657        for _ in 0..100 {
658            if handle.exited().expect("exited poll on zombie") {
659                observed_exit = true;
660                break;
661            }
662            std::thread::sleep(std::time::Duration::from_millis(10));
663        }
664        assert!(observed_exit, "expected exited() on unreaped zombie");
665        let sig_err = handle.terminate().unwrap_err();
666        assert!(matches!(sig_err, SysprimsError::NotFound { .. }));
667
668        // Opening a fresh ProcessHandle on an unreaped zombie must also return NotFound.
669        let zombie_open = open_process_handle(pid).unwrap_err();
670        assert!(matches!(zombie_open, SysprimsError::NotFound { .. }));
671
672        let _ = child.wait();
673    }
674
675    #[test]
676    fn process_handle_error_messages_do_not_leak_paths_or_cmdline() {
677        let err = open_process_handle(MAX_SAFE_PID).unwrap_err();
678        let msg = err.to_string();
679        assert!(!msg.contains("/Users/"));
680        assert!(!msg.contains("/home/"));
681        assert!(!msg.contains("sleep"));
682    }
683
684    #[test]
685    #[cfg(unix)]
686    fn process_handle_fd_is_cloexec_and_not_inherited_by_exec_children() {
687        let baseline = std::process::Command::new("sh")
688            .args([
689                "-c",
690                "ls /dev/fd 2>/dev/null || ls /proc/self/fd 2>/dev/null",
691            ])
692            .stdin(std::process::Stdio::null())
693            .output()
694            .expect("list baseline child fds");
695        assert!(baseline.status.success());
696        let baseline_count = String::from_utf8_lossy(&baseline.stdout)
697            .split_whitespace()
698            .filter_map(|s| s.parse::<i32>().ok())
699            .count();
700
701        let mut handles = Vec::new();
702        for _ in 0..8 {
703            let h = open_process_handle(std::process::id()).expect("open self handle");
704            assert!(!h.exited().expect("self is alive"));
705            handles.push(h);
706        }
707
708        let after = std::process::Command::new("sh")
709            .args([
710                "-c",
711                "ls /dev/fd 2>/dev/null || ls /proc/self/fd 2>/dev/null",
712            ])
713            .stdin(std::process::Stdio::null())
714            .output()
715            .expect("list child fds with 8 open ProcessHandles");
716        assert!(after.status.success());
717        let after_count = String::from_utf8_lossy(&after.stdout)
718            .split_whitespace()
719            .filter_map(|s| s.parse::<i32>().ok())
720            .count();
721
722        // A non-CLOEXEC kqueue/pidfd opened in the parent would increase the child's
723        // open FD count by 8. With FD_CLOEXEC set, the child FD count is unchanged.
724        assert_eq!(
725            after_count, baseline_count,
726            "ProcessHandle FDs must not be inherited across exec"
727        );
728        drop(handles);
729    }
730
731    #[test]
732    #[cfg(target_os = "linux")]
733    fn linux_checked_numeric_fallback_works_when_forced() {
734        with_forced_checked_numeric_for_test(|| {
735            let mut child = spawn_sleep_child();
736            let pid = child.id();
737            let handle = open_process_handle(pid).expect("open fallback handle");
738            assert_eq!(handle.binding(), SignalBinding::CheckedNumeric);
739            assert!(!handle.exited().expect("exited check"));
740            let b = handle.force_kill().expect("force_kill via fallback");
741            assert_eq!(b, SignalBinding::CheckedNumeric);
742            let _ = child.wait();
743            assert!(handle.exited().expect("exited after wait"));
744        });
745    }
746}