Skip to main content

rightkit_child_process/
owned.rs

1use crate::process_handle::{lock_child, ProcessHandle};
2#[cfg(unix)]
3use crate::unix_child::{LeaderState, SignalOutcome, SignalTarget};
4use std::{
5    ffi::OsStr,
6    io,
7    num::NonZeroU32,
8    process::{ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus},
9    sync::{Arc, Mutex, MutexGuard},
10    thread,
11    time::{Duration, Instant, SystemTime},
12};
13#[cfg(unix)]
14type PlatformChild = crate::unix_child::UnixChild;
15#[cfg(windows)]
16type PlatformChild = crate::spawn_windows::WindowsChild;
17
18#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
19pub enum JobAssignmentMode {
20    #[default]
21    Strict,
22    BestEffort,
23}
24
25#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
26pub enum UnixContainment {
27    #[default]
28    ProcessGroup,
29    Session,
30}
31
32/// Scheduling priority requested for the child. `Normal` (the default) means "inherit": it
33/// leaves the spawn exactly as it was before this option existed, so the child keeps the
34/// parent's priority class (Windows) or nice value (Unix). It does not reset a lowered parent
35/// back to normal. The other values only lower priority, which needs no
36/// privilege and never raises a value the child already inherits above a lower one.
37///
38/// Windows: `BelowNormal` adds `BELOW_NORMAL_PRIORITY_CLASS` and `Idle` adds
39/// `IDLE_PRIORITY_CLASS` to the creation flags. Unix: the child's nice value is raised to at
40/// least 10 (`BelowNormal`) or 19 (`Idle`) between fork and exec.
41///
42/// `Efficient` is `BelowNormal` plus the platform's energy-efficiency class, for background
43/// work that should not wake the fast cores. Windows: `BELOW_NORMAL_PRIORITY_CLASS` plus
44/// EcoQoS (`PROCESS_POWER_THROTTLING_EXECUTION_SPEED` through `SetProcessInformation`, set
45/// while the child is still suspended; a Windows without EcoQoS ignores it, best effort).
46/// macOS: nice 10 and the `QOS_CLASS_UTILITY` quality of service on the child's initial
47/// thread (set between fork and exec; advisory). Other Unix: nice 10.
48#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
49#[non_exhaustive]
50pub enum ProcessPriority {
51    #[default]
52    Normal,
53    BelowNormal,
54    Idle,
55    Efficient,
56}
57
58impl ProcessPriority {
59    /// Minimum Unix nice value for this priority; `None` leaves the inherited value alone.
60    #[cfg(unix)]
61    pub(crate) fn nice_floor(self) -> Option<libc::c_int> {
62        match self {
63            Self::Normal => None,
64            Self::BelowNormal | Self::Efficient => Some(10),
65            Self::Idle => Some(19),
66        }
67    }
68}
69
70#[derive(Clone, Copy, Debug, Eq, PartialEq)]
71pub struct TerminationOptions {
72    /// Send TERM immediately on Unix, then KILL after this tree-wide grace.
73    pub grace: Duration,
74    /// Passed to TerminateJobObject/TerminateProcess on Windows.
75    pub windows_exit_code: u32,
76}
77impl Default for TerminationOptions {
78    fn default() -> Self {
79        Self {
80            grace: Duration::ZERO,
81            windows_exit_code: 1,
82        }
83    }
84}
85impl TerminationOptions {
86    pub fn with_grace(mut self, grace: Duration) -> Self {
87        self.grace = grace;
88        self
89    }
90    pub fn with_windows_exit_code(mut self, code: u32) -> Self {
91        self.windows_exit_code = code;
92        self
93    }
94}
95
96/// Every failed assignment in a best-effort Windows spawn is retained.
97/// Windows job breakaway policy for an owned child; Unix ignores it.
98#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
99pub(crate) enum BreakawayMode {
100    /// Full containment.
101    #[default]
102    None,
103    /// `JOB_OBJECT_LIMIT_BREAKAWAY_OK`: only processes that ask leave the job.
104    Explicit,
105    /// `BREAKAWAY_OK` plus `SILENT_BREAKAWAY_OK`: every created process leaves the job.
106    Silent,
107}
108
109#[derive(Debug)]
110pub struct JobAssignmentFailure {
111    pub stage: &'static str,
112    pub error: io::Error,
113}
114impl JobAssignmentFailure {
115    pub fn raw_os_error(&self) -> Option<i32> {
116        self.error.raw_os_error()
117    }
118}
119
120/// Borrowed OS handle/fd value; keep it valid until spawn returns.
121#[cfg(windows)]
122pub type RawHandleOrFd = std::os::windows::io::RawHandle;
123#[cfg(unix)]
124pub type RawHandleOrFd = std::os::fd::RawFd;
125#[cfg(windows)]
126type InheritedValue = usize;
127#[cfg(unix)]
128type InheritedValue = RawHandleOrFd;
129
130#[derive(Debug)]
131pub struct OwnedCommand {
132    command: Command,
133    windows_hidden: bool,
134    windows_breakaway: BreakawayMode,
135    caller_job: CallerJob,
136    job_assignment: JobAssignmentMode,
137    unix_containment: UnixContainment,
138    process_priority: ProcessPriority,
139    kill_on_parent_exit: bool,
140    // Set by `spawn_suspended`: Windows leaves the child suspended until `OwnedChild::resume`.
141    hold_suspended: bool,
142    // None preserves the existing unbounded partial-spawn reap.
143    partial_spawn_cleanup_timeout: Option<Duration>,
144    inherited_handles: Option<Vec<InheritedValue>>,
145    #[cfg(windows)]
146    windows_spawn_config: Option<crate::WindowsSpawnConfig>,
147    #[cfg(windows)]
148    windows_spawn_config_auto: bool,
149    env_cleared: bool,
150}
151#[cfg(windows)]
152type CallerJob = Option<std::os::windows::io::OwnedHandle>;
153#[cfg(not(windows))]
154type CallerJob = Option<std::convert::Infallible>;
155
156impl OwnedCommand {
157    pub fn new(program: impl AsRef<OsStr>) -> Self {
158        let command = Self::from_command(Command::new(program));
159        #[cfg(windows)]
160        let command = {
161            let mut command = command;
162            // Only a fresh Command has known inherited stdio/environment defaults. The
163            // config is marked auto, and `command_mut` clears it.
164            command.windows_spawn_config = Some(crate::WindowsSpawnConfig::default());
165            command.windows_spawn_config_auto = true;
166            command
167        };
168        command
169    }
170    /// GUI/service children are hidden on Windows by default. A wrapped `Command` may carry
171    /// stdio, environment and raw-argument settings this crate cannot read back, so on
172    /// Windows an allowlisted spawn (`inherit_handles_only`) from `from_command` requires an
173    /// explicit `windows_spawn_config`. The crate never widens what a child inherits by
174    /// default.
175    pub fn from_command(command: Command) -> Self {
176        Self {
177            command,
178            windows_hidden: true,
179            windows_breakaway: BreakawayMode::None,
180            caller_job: None,
181            job_assignment: JobAssignmentMode::Strict,
182            unix_containment: UnixContainment::ProcessGroup,
183            process_priority: ProcessPriority::Normal,
184            kill_on_parent_exit: false,
185            hold_suspended: false,
186            partial_spawn_cleanup_timeout: None,
187            inherited_handles: None,
188            #[cfg(windows)]
189            windows_spawn_config: None,
190            #[cfg(windows)]
191            windows_spawn_config_auto: false,
192            env_cleared: false,
193        }
194    }
195    pub fn command_mut(&mut self) -> &mut Command {
196        #[cfg(windows)]
197        if self.windows_spawn_config_auto {
198            // A mutable std Command can change settings with no stable getter.
199            self.windows_spawn_config = None;
200        }
201        &mut self.command
202    }
203    /// Inherit only these handles/fds plus configured stdio; values stay caller-owned.
204    pub fn inherit_handles_only(
205        &mut self,
206        handles: impl IntoIterator<Item = RawHandleOrFd>,
207    ) -> &mut Self {
208        #[cfg(windows)]
209        let handles = handles.into_iter().map(|handle| handle as usize).collect();
210        #[cfg(unix)]
211        let handles = handles.into_iter().collect();
212        self.inherited_handles = Some(handles);
213        self
214    }
215    /// Supply opaque stdio/environment/raw-arg settings for native allowlisted spawns.
216    /// Required after from_command/command_mut when inherit_handles_only is set.
217    /// Ordinary std spawns ignore it; fresh new() Commands have known defaults.
218    #[cfg(windows)]
219    pub fn windows_spawn_config(&mut self, config: crate::WindowsSpawnConfig) -> &mut Self {
220        self.windows_spawn_config = Some(config);
221        self.windows_spawn_config_auto = false;
222        self
223    }
224    /// Clear environment, then copy only named variables set in this process.
225    pub fn env_allowlist<I, S>(&mut self, keys: I) -> &mut Self
226    where
227        I: IntoIterator<Item = S>,
228        S: AsRef<OsStr>,
229    {
230        let kept: Vec<_> = keys
231            .into_iter()
232            .filter_map(|k| std::env::var_os(k.as_ref()).map(|v| (k.as_ref().to_os_string(), v)))
233            .collect();
234        self.command.env_clear();
235        self.env_cleared = true;
236        for (k, v) in kept {
237            self.command.env(k, v);
238        }
239        self
240    }
241    /// [`Self::env_allowlist`] over [`DEFAULT_ENV_ALLOWLIST`] plus `extra` (a consumer's own
242    /// variables, for instance a model-cache location). Call it once: like `env_allowlist` it
243    /// starts from an empty environment, so a second call drops what the first kept.
244    pub fn env_allowlist_with_defaults<I, S>(&mut self, extra: I) -> &mut Self
245    where
246        I: IntoIterator<Item = S>,
247        S: AsRef<OsStr>,
248    {
249        let keys: Vec<std::ffi::OsString> = DEFAULT_ENV_ALLOWLIST
250            .iter()
251            .map(std::ffi::OsString::from)
252            .chain(extra.into_iter().map(|k| k.as_ref().to_os_string()))
253            .collect();
254        self.env_allowlist(keys)
255    }
256    /// True once [`Self::env_allowlist`] (or `env_allowlist_with_defaults`) cleared the inherited
257    /// environment on this command. A `Command` that was cleared with `env_clear` directly, or
258    /// wrapped by `from_command` after it was cleared, reads `false`: the state is not observable
259    /// from `std::process::Command`.
260    pub fn env_is_cleared(&self) -> bool {
261        self.env_cleared
262    }
263    pub fn env_strip<I, S>(&mut self, keys: I) -> &mut Self
264    where
265        I: IntoIterator<Item = S>,
266        S: AsRef<OsStr>,
267    {
268        for k in keys {
269            self.command.env_remove(k);
270        }
271        self
272    }
273    /// Compatibility no-op: hidden is already the default.
274    pub fn windows_hide(&mut self) -> &mut Self {
275        self.windows_hidden = true;
276        self
277    }
278    /// Windows: leaves the console window visible, clearing the hidden default, for a
279    /// user-facing program (an editor, a terminal at a project path) that must keep its window.
280    /// Pair it with [`spawn_uncontained_detached`](Self::spawn_uncontained_detached) for a
281    /// fire-and-forget launch. Unix ignores it.
282    pub fn windows_visible(&mut self) -> &mut Self {
283        self.windows_hidden = false;
284        self
285    }
286    /// Windows: explicit-only breakaway (`JOB_OBJECT_LIMIT_BREAKAWAY_OK`). A process in the
287    /// job leaves it only by asking (`CREATE_BREAKAWAY_FROM_JOB`); every descendant that does
288    /// not ask stays contained and is terminated with the job. Dropping the owned child still
289    /// terminates the helper's tree; a grandchild that asked and broke away stays running.
290    /// `false` restores full containment. Unix ignores it. For descendants that escape without
291    /// asking, see [`windows_allow_silent_breakaway`](Self::windows_allow_silent_breakaway).
292    pub fn windows_allow_breakaway(&mut self, allow: bool) -> &mut Self {
293        self.windows_breakaway = if allow {
294            BreakawayMode::Explicit
295        } else {
296            BreakawayMode::None
297        };
298        self
299    }
300    /// Windows: silent breakaway (`JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK` plus `BREAKAWAY_OK`).
301    /// Every process the job's processes create is outside the job without asking, so
302    /// descendants are NOT contained and survive the helper. Use only for a helper whose
303    /// children must all outlive it. `false` restores full containment. Unix ignores it.
304    pub fn windows_allow_silent_breakaway(&mut self, allow: bool) -> &mut Self {
305        self.windows_breakaway = if allow {
306            BreakawayMode::Silent
307        } else {
308            BreakawayMode::None
309        };
310        self
311    }
312    /// Duplicate caller job; assign before the empty nested RightKit job.
313    #[cfg(windows)]
314    pub fn windows_job(
315        &mut self,
316        job: std::os::windows::io::BorrowedHandle<'_>,
317    ) -> io::Result<&mut Self> {
318        self.caller_job = Some(job.try_clone_to_owned()?);
319        Ok(self)
320    }
321    /// Ignored on Unix. BestEffort reports errors on OwnedChild.
322    pub fn job_assignment_mode(&mut self, mode: JobAssignmentMode) -> &mut Self {
323        self.job_assignment = mode;
324        self
325    }
326    /// Ignored on Windows. Session runs setsid before exec.
327    pub fn unix_containment(&mut self, mode: UnixContainment) -> &mut Self {
328        self.unix_containment = mode;
329        self
330    }
331    /// Scheduling priority for the child. The default, `ProcessPriority::Normal`, adds nothing
332    /// to the spawn. See `ProcessPriority` for the Windows and Unix mappings. Applies to
333    /// detached spawns too.
334    pub fn process_priority(&mut self, priority: ProcessPriority) -> &mut Self {
335        self.process_priority = priority;
336        self
337    }
338    /// Opt-in, off by default. Linux only: the kernel sends `SIGTERM` to the direct child
339    /// (`PR_SET_PDEATHSIG`) when the thread that spawned it exits, which includes this
340    /// process dying without running cleanup (for example SIGKILL). The signal reaches the
341    /// direct child only, never the rest of its group, it can be caught, and there is no
342    /// `SIGKILL` escalation. It is keyed to the spawning *thread*, so spawn from a thread
343    /// that lives as long as the child.
344    ///
345    /// macOS has no `PR_SET_PDEATHSIG`, so the tie is a small watchdog process started right
346    /// after the child (a `kqueue` with `EVFILT_PROC`/`NOTE_EXIT` on this process and on the
347    /// child; see `process_unix::arm_parent_death_watch`). When this process dies, SIGKILL
348    /// included, the watchdog sends `SIGTERM` to the child's whole process group and `SIGKILL`
349    /// two seconds later. Differences from Linux: the trigger is the whole process exiting,
350    /// not the spawning thread; the signal goes to the group and escalates; it costs one
351    /// extra helper process per tied child (it exits when the child or this process does);
352    /// the child runs untied between its spawn and the moment `spawn` returns (a few
353    /// milliseconds), and `spawn` kills the child and fails if the watchdog cannot be armed.
354    ///
355    /// Other Unix hosts have no parent-death primitive this crate relies on: the spawn fails
356    /// with `ErrorKind::Unsupported` before anything is started, rather than run the child
357    /// untied. Windows ignores the option because kill-on-close job objects already cover
358    /// parent death. Rejected (`InvalidInput`) for detached spawns.
359    pub fn kill_on_parent_exit(&mut self, enabled: bool) -> &mut Self {
360        self.kill_on_parent_exit = enabled;
361        self
362    }
363    /// Bound failed-spawn cleanup. Timed-out children go to a background reaper.
364    pub fn partial_spawn_cleanup_timeout(&mut self, timeout: Duration) -> &mut Self {
365        self.partial_spawn_cleanup_timeout = Some(timeout);
366        self
367    }
368    pub fn spawn(self) -> io::Result<OwnedChild> {
369        self.spawn_inner(false, false, None)
370    }
371    /// Like [`OwnedCommand::spawn`], but on Windows the child is created suspended, assigned to
372    /// its Job Object, and held there: it executes no instruction until
373    /// [`OwnedChild::resume`] is called. A caller can persist the child's identity (pid and
374    /// start time) first, then release it. Dropping a child that was never resumed terminates it
375    /// like any owned child.
376    ///
377    /// Unix has no suspended creation: this is `spawn`, the child runs at once, and `resume` is
378    /// a no-op that returns `Ok`. A caller that needs a hold on Unix gates the child itself (for
379    /// example a pipe the child blocks reading).
380    pub fn spawn_suspended(mut self) -> io::Result<OwnedChild> {
381        self.hold_suspended = true;
382        self.spawn_inner(false, false, None)
383    }
384    /// Shared launch with no owner job or terminate-on-drop. Unix uses setsid.
385    /// Stdio follows Command: dropping piped stdin can still deliver EOF.
386    ///
387    /// Windows first asks to break away from the caller's job object
388    /// (`CREATE_BREAKAWAY_FROM_JOB`). If the caller's job denies breakaway
389    /// (`ERROR_ACCESS_DENIED`), the launch is retried once without it, as
390    /// `CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP` (`DETACHED_PROCESS` if `show_window`) with the same stdio and handle
391    /// allowlist (an ordinary spawn without an allowlist still inherits what std inherits).
392    /// The child is then detached from the console and process group but stays inside the
393    /// caller's job, so the job's limits (including kill-on-close) still reach it. Check
394    /// [`OwnedChild::stayed_in_parent_job`] to learn which happened. A caller that must not
395    /// run inside the parent's job uses
396    /// [`spawn_uncontained_detached_strict`](Self::spawn_uncontained_detached_strict). Any
397    /// other launch failure is returned as is, without a retry. Unix behaviour is unchanged.
398    pub fn spawn_uncontained_detached(self) -> io::Result<OwnedChild> {
399        self.spawn_inner_with(true, false, None, true)
400    }
401    /// Like [`spawn_uncontained_detached`](Self::spawn_uncontained_detached), but never falls
402    /// back. On Windows, when the caller's job denies breakaway the launch fails with an
403    /// [`io::Error`] of kind `PermissionDenied` wrapping [`BreakawayDenied`] (recover it with
404    /// `error.get_ref().and_then(|e| e.downcast_ref::<BreakawayDenied>())`), and nothing is
405    /// started. On Unix this is identical to `spawn_uncontained_detached`.
406    pub fn spawn_uncontained_detached_strict(self) -> io::Result<OwnedChild> {
407        match self.spawn_inner_with(true, false, None, false) {
408            Err(error) if cfg!(windows) && is_denied_breakaway(&error) => Err(io::Error::new(
409                io::ErrorKind::PermissionDenied,
410                BreakawayDenied,
411            )),
412            other => other,
413        }
414    }
415    fn spawn_inner(
416        self,
417        detached: bool,
418        fail_after_spawn: bool,
419        captured_pid: Option<Arc<std::sync::atomic::AtomicU32>>,
420    ) -> io::Result<OwnedChild> {
421        self.spawn_inner_with(detached, fail_after_spawn, captured_pid, false)
422    }
423    fn spawn_inner_with(
424        mut self,
425        detached: bool,
426        fail_after_spawn: bool,
427        captured_pid: Option<Arc<std::sync::atomic::AtomicU32>>,
428        in_job_fallback: bool,
429    ) -> io::Result<OwnedChild> {
430        if detached && self.caller_job.is_some() {
431            return Err(io::Error::new(
432                io::ErrorKind::InvalidInput,
433                "detached launch cannot join a caller job",
434            ));
435        }
436        if detached && self.kill_on_parent_exit {
437            return Err(io::Error::new(
438                io::ErrorKind::InvalidInput,
439                "kill_on_parent_exit cannot combine with a detached launch",
440            ));
441        }
442        #[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
443        if self.kill_on_parent_exit {
444            return Err(io::Error::new(
445                io::ErrorKind::Unsupported,
446                "kill_on_parent_exit is supported on Linux and macOS only",
447            ));
448        }
449        #[cfg(unix)]
450        {
451            use std::os::unix::process::CommandExt;
452            let session = detached || self.unix_containment == UnixContainment::Session;
453            let nice_floor = self.process_priority.nice_floor();
454            #[cfg(target_os = "macos")]
455            let utility_qos = self.process_priority == ProcessPriority::Efficient;
456            let inheritance = self
457                .inherited_handles
458                .take()
459                .map(crate::process_unix::Inheritance::new)
460                .transpose()?;
461            // The supervisor's pid, read here and compared in the child (see `die_with_parent`).
462            #[cfg(target_os = "linux")]
463            let supervisor = self
464                .kill_on_parent_exit
465                // SAFETY: getpid has no preconditions.
466                .then(|| unsafe { libc::getpid() });
467            // Only async-signal-safe libc calls run between fork and exec.
468            unsafe {
469                self.command.pre_exec(move || {
470                    let result = if session {
471                        libc::setsid()
472                    } else {
473                        libc::setpgid(0, 0)
474                    };
475                    if result < 0 {
476                        return Err(io::Error::last_os_error());
477                    }
478                    if let Some(floor) = nice_floor {
479                        crate::process_unix::raise_nice_to(floor)?;
480                    }
481                    #[cfg(target_os = "macos")]
482                    if utility_qos {
483                        crate::process_unix::set_utility_qos();
484                    }
485                    if let Some(inheritance) = &inheritance {
486                        inheritance.apply()?;
487                    }
488                    #[cfg(target_os = "linux")]
489                    if let Some(supervisor) = supervisor {
490                        crate::process_unix::die_with_parent(supervisor)?;
491                    }
492                    Ok(())
493                });
494            }
495        }
496        #[cfg(windows)]
497        crate::process_windows::configure(
498            &mut self.command,
499            detached,
500            self.windows_hidden,
501            self.process_priority,
502        );
503        #[cfg(unix)]
504        let _ = (
505            self.windows_hidden,
506            self.windows_breakaway,
507            self.job_assignment,
508        );
509        #[cfg(windows)]
510        let _ = (self.unix_containment, self.kill_on_parent_exit);
511        let spawned_at = SystemTime::now();
512        let hold_suspended = self.hold_suspended && !detached;
513        #[cfg(unix)]
514        let _ = hold_suspended;
515        #[cfg(unix)]
516        let child = {
517            let mut child = crate::unix_child::UnixChild::new(self.command.spawn()?);
518            // A child whose pid cannot be tied to it is stopped here, while the pid is
519            // certainly still its own: no later signal could be proven to reach it.
520            child.require_identity()?;
521            // macOS: the tie is a watchdog armed while the pid is still certainly ours. A
522            // child that could not be tied is stopped, never handed out untied.
523            #[cfg(target_os = "macos")]
524            if self.kill_on_parent_exit {
525                if let Err(error) = crate::process_unix::arm_parent_death_watch(child.id()) {
526                    let _ = child.signal(SignalTarget::Group, libc::SIGKILL);
527                    let _ = child.kill();
528                    let _ = child.wait();
529                    return Err(error);
530                }
531            }
532            child
533        };
534        #[cfg(windows)]
535        let (child, stayed_in_parent_job) = match self.inherited_handles.as_deref() {
536            None => {
537                // An ordinary spawn inherits every inheritable handle. Held so it never runs
538                // while an allowlisted spawn has private handles raised.
539                let _spawning = crate::spawn_windows::spawn_guard();
540                match self.command.spawn() {
541                    Ok(child) => (PlatformChild::from(child), false),
542                    // The caller's job denied breakaway: one retry, detached but inside it.
543                    Err(error)
544                        if detached
545                            && in_job_fallback
546                            && crate::process_windows::is_breakaway_denied(&error) =>
547                    {
548                        crate::process_windows::configure_in_job_detached(
549                            &mut self.command,
550                            self.windows_hidden,
551                            self.process_priority,
552                        );
553                        (PlatformChild::from(self.command.spawn()?), true)
554                    }
555                    Err(error) => return Err(error),
556                }
557            }
558            Some(handles) => {
559                let config = self.windows_spawn_config.take().ok_or_else(|| {
560                    io::Error::new(io::ErrorKind::InvalidInput,
561                        "allowlisted Windows spawn requires windows_spawn_config for opaque Command settings")
562                })?;
563                crate::spawn_windows::spawn(
564                    &self.command,
565                    config,
566                    handles,
567                    detached,
568                    self.windows_hidden,
569                    self.process_priority,
570                    self.env_cleared,
571                    self.partial_spawn_cleanup_timeout,
572                    in_job_fallback,
573                )?
574            }
575        };
576        #[cfg(not(windows))]
577        let _ = in_job_fallback;
578        #[cfg(not(windows))]
579        let stayed_in_parent_job = false;
580        let pid = child.id();
581        if let Some(captured) = captured_pid {
582            captured.store(pid, std::sync::atomic::Ordering::SeqCst);
583        }
584        let child = Arc::new(Mutex::new(child));
585        let handle = match ProcessHandle::new(&child, spawned_at) {
586            Ok(handle) => handle,
587            Err(error) => {
588                cleanup_direct(child, self.partial_spawn_cleanup_timeout);
589                return Err(error);
590            }
591        };
592        let mut partial = PartialChild {
593            child: Some(OwnedChild {
594                child,
595                handle,
596                pid,
597                detached,
598                terminate_on_drop: !detached,
599                drop_reap_timeout: DEFAULT_DROP_REAP_TIMEOUT,
600                tree_terminated: false,
601                assignment_failures: Vec::new(),
602                suspended: std::sync::atomic::AtomicBool::new(cfg!(windows) && hold_suspended),
603                stayed_in_parent_job,
604                #[cfg(windows)]
605                job: None,
606            }),
607            timeout: self.partial_spawn_cleanup_timeout,
608        };
609        #[cfg(windows)]
610        if !detached {
611            let owned = partial.child.as_mut().expect("partial child is present");
612            crate::process_windows::assign_jobs(
613                &owned.handle,
614                self.caller_job.take(),
615                self.job_assignment,
616                self.windows_breakaway,
617                &mut owned.job,
618                &mut owned.assignment_failures,
619            )?;
620        }
621        #[cfg(windows)]
622        {
623            let owned = partial.child.as_ref().expect("partial child is present");
624            if self.process_priority == ProcessPriority::Efficient {
625                // Best effort: EcoQoS is a hint and older Windows builds lack it.
626                let _ = crate::process_windows::apply_efficiency(&*owned.child());
627            }
628            if !hold_suspended {
629                owned.child().resume(detached)?;
630            }
631        }
632        if fail_after_spawn {
633            return Err(io::Error::other("injected post-spawn wrapping failure"));
634        }
635        let owned = partial.child.take().expect("partial child is present");
636        if !detached {
637            // Detached children are deliberately not owned: they outlive their handle.
638            #[cfg(unix)]
639            crate::registry::register(&owned.child, owned.pid);
640            #[cfg(windows)]
641            crate::registry::register(
642                &owned.child,
643                &owned.handle,
644                owned
645                    .job
646                    .as_ref()
647                    .map_or_else(std::sync::Weak::new, std::sync::Arc::downgrade),
648                owned.pid,
649            );
650        }
651        Ok(owned)
652    }
653}
654
655/// The error source returned (inside an [`io::Error`] of kind `PermissionDenied`) by
656/// [`OwnedCommand::spawn_uncontained_detached_strict`] on Windows when the caller's job object
657/// denies `CREATE_BREAKAWAY_FROM_JOB`. The OS reports this as `ERROR_ACCESS_DENIED`, which this
658/// crate cannot tell apart from other access-denied launch failures; a job that forbids
659/// breakaway is the cause this crate expects.
660#[derive(Clone, Copy, Debug, Eq, PartialEq)]
661pub struct BreakawayDenied;
662
663impl std::fmt::Display for BreakawayDenied {
664    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
665        f.write_str(
666            "detached launch denied: the caller's job object does not allow breakaway \
667             (ERROR_ACCESS_DENIED); no fallback was attempted",
668        )
669    }
670}
671
672impl std::error::Error for BreakawayDenied {}
673
674#[cfg(windows)]
675fn is_denied_breakaway(error: &io::Error) -> bool {
676    crate::process_windows::is_breakaway_denied(error)
677}
678#[cfg(not(windows))]
679fn is_denied_breakaway(_error: &io::Error) -> bool {
680    false
681}
682
683/// How long `Drop` waits for a killed leader to be reaped before handing the reap to a
684/// background thread.
685pub const DEFAULT_DROP_REAP_TIMEOUT: Duration = Duration::from_secs(2);
686
687pub const DEFAULT_ENV_ALLOWLIST: &[&str] = &[
688    "PATH",
689    "HOME",
690    "USER",
691    "LOGNAME",
692    "LANG",
693    "LC_ALL",
694    "TMPDIR",
695    "TEMP",
696    "TMP",
697    "SystemRoot",
698    "SYSTEMROOT",
699    "USERPROFILE",
700    "APPDATA",
701    "LOCALAPPDATA",
702    "ProgramData",
703    "COMSPEC",
704    "PATHEXT",
705    "XDG_DATA_HOME",
706    "XDG_RUNTIME_DIR",
707];
708
709#[derive(Debug)]
710pub struct OwnedChild {
711    child: Arc<Mutex<PlatformChild>>,
712    handle: ProcessHandle,
713    // Captured before any wait can reap the direct child.
714    pid: u32,
715    detached: bool,
716    terminate_on_drop: bool,
717    drop_reap_timeout: Duration,
718    tree_terminated: bool,
719    assignment_failures: Vec<JobAssignmentFailure>,
720    // True from `spawn_suspended` (Windows) until `resume` releases the child.
721    suspended: std::sync::atomic::AtomicBool,
722    // Windows detached launch only: breakaway was denied and the child runs inside the parent's job.
723    stayed_in_parent_job: bool,
724    // Shared so the owned-children registry can reach the job without keeping it open
725    // (it holds a `Weak`): the kill-on-close job still closes with this child.
726    #[cfg(windows)]
727    job: Option<std::sync::Arc<crate::process_windows::KillOnCloseJob>>,
728}
729/// The result of [`OwnedChild::terminate_tree_deep`].
730#[derive(Clone, Debug, Eq, PartialEq)]
731pub struct TreeTermination {
732    /// The leader's exit status.
733    pub status: ExitStatus,
734    /// What happened to the descendants recorded before the leader was stopped.
735    pub descendants: crate::SweepReport,
736}
737#[derive(Clone, Copy, Debug, Eq, PartialEq)]
738pub enum ReapOutcome {
739    Exited(ExitStatus),
740    TimedOut,
741}
742#[derive(Clone, Copy, Debug, Eq, PartialEq)]
743pub enum WaitOutcome {
744    Exited(ExitStatus),
745    Terminated(ExitStatus),
746}
747
748impl OwnedChild {
749    pub fn id(&self) -> u32 {
750        self.pid
751    }
752    /// True only for a Windows [`OwnedCommand::spawn_uncontained_detached`] child that could
753    /// not break away because the caller's job object denied it, so it was launched detached
754    /// but still inside that job (the job's limits, such as kill-on-close, still reach it).
755    /// False for every other child, including every Unix child and any child that broke away.
756    pub fn stayed_in_parent_job(&self) -> bool {
757        self.stayed_in_parent_job
758    }
759    /// Borrow child state, including stdio, wait and try_wait. Windows uses a
760    /// native view with std pipe types for both spawn paths; Unix uses `UnixChild`, which
761    /// has the same members and does not expose the std `Child`. Release this guard
762    /// before another accessor or exit reader; it holds the shared reap lock.
763    ///
764    /// Unix: a `wait` or `try_wait` through the guard that reaps the leader permanently
765    /// ends process-group signalling for this child, exactly like `OwnedChild::wait`.
766    ///
767    /// Unix: `wait` through the guard holds the shared lock until the child has exited, because
768    /// the guard is the lock. A bounded wait on a `ProcessHandle` clone, `kill`,
769    /// `terminate_tree` and `Drop` on other threads queue behind it and can exceed their own
770    /// deadlines, as with `std::process::Child::wait` through this accessor in 0.3.3. Wait
771    /// through `OwnedChild::wait`/`wait_timeout` or a `ProcessHandle` when anything else must
772    /// stay live meanwhile. (Windows: `WindowsChild::wait` through the guard blocks in
773    /// `WaitForSingleObject` while holding the lock, as in 0.3.3.)
774    pub fn child(&self) -> MutexGuard<'_, PlatformChild> {
775        lock_child(&self.child)
776    }
777    /// Release a child created by [`OwnedCommand::spawn_suspended`]. It is already in its Job
778    /// Object; this lets it run. Returns `Ok` and does nothing for a child that is not held
779    /// (an ordinary spawn, a child already resumed, and every Unix child). On error the child
780    /// stays held and `resume` can be retried.
781    pub fn resume(&self) -> io::Result<()> {
782        if self
783            .suspended
784            .swap(false, std::sync::atomic::Ordering::SeqCst)
785        {
786            #[cfg(windows)]
787            if let Err(error) = self.child().resume(self.detached) {
788                self.suspended
789                    .store(true, std::sync::atomic::Ordering::SeqCst);
790                return Err(error);
791            }
792        }
793        Ok(())
794    }
795    /// True while a child from [`OwnedCommand::spawn_suspended`] has not been resumed.
796    pub fn is_suspended(&self) -> bool {
797        self.suspended.load(std::sync::atomic::Ordering::SeqCst)
798    }
799    /// Runs `act` with the leader's pid while the leader is proven to be this child and
800    /// unreaped, holding the shared lock so no reap can fall between the proof and `act`.
801    /// Returns `Ok(None)` without calling `act` once the leader has been reaped or its pid no
802    /// longer provably names it. For code that must signal by pid (a descendant sweep) and
803    /// would otherwise act on a number that may have been recycled. The lock is held for as
804    /// long as `act` runs (that is what keeps a reap out), so every other thread's wait,
805    /// including a bounded one, is delayed by that long: keep `act` short, and never call back
806    /// into this child from it. Windows has no recyclable-pid hazard here and always runs it.
807    pub fn while_unreaped<R>(&self, act: impl FnOnce(u32) -> R) -> io::Result<Option<R>> {
808        #[cfg(unix)]
809        {
810            let mut child = lock_child(&self.child);
811            if child.leader_state()? == LeaderState::Reaped {
812                return Ok(None);
813            }
814            Ok(Some(act(self.pid)))
815        }
816        #[cfg(windows)]
817        Ok(Some(act(self.pid)))
818    }
819    pub fn take_stdin(&mut self) -> Option<ChildStdin> {
820        self.child().stdin.take()
821    }
822    /// Closes the child's stdin (delivering EOF) without waiting. Idempotent: a child whose
823    /// stdin was taken or already closed is untouched. For a child that already exited this
824    /// is a harmless drop of the unused pipe end, never an error.
825    pub fn close_stdin(&mut self) {
826        drop(self.child().stdin.take());
827    }
828    pub fn take_stdout(&mut self) -> Option<ChildStdout> {
829        self.child().stdout.take()
830    }
831    pub fn take_stderr(&mut self) -> Option<ChildStderr> {
832        self.child().stderr.take()
833    }
834    pub fn job_assignment_failures(&self) -> &[JobAssignmentFailure] {
835        &self.assignment_failures
836    }
837    /// An independent exit reader. A monitor thread that only needs to learn that the leader
838    /// exited should call [`ProcessHandle::wait_exited`], which does not reap; `wait` reaps, and
839    /// on Unix that ends the owner's ability to signal descendants that outlive the leader.
840    pub fn process_handle(&self) -> io::Result<ProcessHandle> {
841        self.handle.try_clone()
842    }
843    pub fn creation_time(&self) -> Option<SystemTime> {
844        self.handle.creation_time()
845    }
846    #[cfg(windows)]
847    pub fn creation_time_ticks(&self) -> Option<u64> {
848        self.handle.creation_time_ticks()
849    }
850    pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
851        // Through the handle so the reap also seals the process group's state.
852        self.handle.try_wait()
853    }
854    // Preserve std Child::wait's stdin-close behavior. ProcessHandle performs
855    // native blocking waits & keeps Unix reap results in std's shared cache.
856    pub fn wait(&mut self) -> io::Result<ExitStatus> {
857        drop(self.child().stdin.take());
858        self.handle.wait()
859    }
860    pub fn wait_timeout(&mut self, timeout: Duration) -> io::Result<Option<ExitStatus>> {
861        self.handle.wait_timeout(timeout)
862    }
863    /// Asks the tree to stop, waits up to `grace` for the leader, then forces the tree down.
864    ///
865    /// Unix: TERM goes to the group while the leader is still unreaped. If the leader exits
866    /// within `grace` the result is `Exited`, but descendants that outlived it (or ignored
867    /// TERM) are killed before the leader is reaped, while it still pins the group id. If it
868    /// does not exit in time the whole group is killed and the result is `Terminated`.
869    ///
870    /// Windows: if the leader exits within `grace` the result is `Exited` with its status, but
871    /// the retained job is terminated first, so descendants that outlived it do not survive.
872    pub fn wait_or_kill(&mut self, grace: Duration) -> io::Result<WaitOutcome> {
873        self.wait_or_kill_inner(grace, true)
874    }
875    /// Like [`wait_or_kill`](Self::wait_or_kill) but without the opening TERM on Unix: the
876    /// leader gets the whole `grace` to exit on its own (for example after its stdin was
877    /// closed) before the tree is killed. A leader that exits in time is never signalled, so
878    /// its status is its own; descendants are still killed before the reap. Windows has no
879    /// TERM step, so it behaves exactly like `wait_or_kill`.
880    pub fn wait_then_kill(&mut self, grace: Duration) -> io::Result<WaitOutcome> {
881        self.wait_or_kill_inner(grace, false)
882    }
883    fn wait_or_kill_inner(&mut self, grace: Duration, term_first: bool) -> io::Result<WaitOutcome> {
884        #[cfg(not(unix))]
885        let _ = term_first;
886        #[cfg(unix)]
887        {
888            if term_first && !self.tree_terminated {
889                self.signal(libc::SIGTERM)?;
890            }
891            // Looks without reaping until the leader has exited or the grace has passed.
892            if self.handle.wait_exited_timeout(grace)? {
893                // Exited, not reaped yet: the zombie still pins the group id, so the
894                // stragglers can be killed safely, and only then reaped. (If a handle clone
895                // reaped it, the signal is a no-op, the cached status is returned and group
896                // signalling is over.)
897                self.force_kill(1)?;
898                return self.wait().map(WaitOutcome::Exited);
899            }
900            self.terminate_tree().map(WaitOutcome::Terminated)
901        }
902        #[cfg(windows)]
903        {
904            if let Some(status) = self.wait_timeout(grace)? {
905                // The leader left, but descendants may still be in the retained job (and hold
906                // the pipes). Bring the job down before reporting; the leader's own status,
907                // already collected, is what the caller gets.
908                self.force_kill(1)?;
909                return Ok(WaitOutcome::Exited(status));
910            }
911            self.terminate_tree().map(WaitOutcome::Terminated)
912        }
913    }
914    /// Immediate forced termination, preserving the existing default.
915    /// Windows: the retained job is signalled even after the parent was reaped.
916    /// Unix: the group is signalled only while the leader is unreaped (see the type
917    /// documentation); once any path has reaped it, only the reap result is returned.
918    pub fn terminate_tree(&mut self) -> io::Result<ExitStatus> {
919        self.force_kill(1)?;
920        self.wait()
921    }
922    /// Unix: TERM now, tree-wide grace, then KILL, all while the leader is unreaped (an
923    /// exited leader stays unreaped until this call reaps it, so descendants still receive
924    /// the KILL). If another path already reaped the leader, nothing is signalled.
925    /// Windows: immediately terminate retained job with supplied exit code.
926    pub fn terminate_tree_with_options(
927        &mut self,
928        options: TerminationOptions,
929    ) -> io::Result<ExitStatus> {
930        self.start_termination(options)?;
931        self.wait()
932    }
933    pub fn terminate_tree_bounded(&mut self, timeout: Duration) -> io::Result<ReapOutcome> {
934        self.terminate_tree_bounded_with_options(timeout, TerminationOptions::default())
935    }
936    /// timeout covers grace plus reap; grace is clipped to timeout.
937    pub fn terminate_tree_bounded_with_options(
938        &mut self,
939        timeout: Duration,
940        mut options: TerminationOptions,
941    ) -> io::Result<ReapOutcome> {
942        let started = Instant::now();
943        options.grace = options.grace.min(timeout);
944        self.start_termination(options)?;
945        Ok(
946            match self.wait_timeout(timeout.saturating_sub(started.elapsed()))? {
947                Some(status) => ReapOutcome::Exited(status),
948                None => ReapOutcome::TimedOut,
949            },
950        )
951    }
952    /// On-demand termination of the whole tree, for a child that is not terminated on drop (a
953    /// [`spawn_uncontained_detached`](OwnedCommand::spawn_uncontained_detached) child whose
954    /// helpers should die now) as well as for an ordinary one. Unlike
955    /// [`terminate_tree_with_options`](Self::terminate_tree_with_options), a detached child's
956    /// descendants are not left alone:
957    ///
958    /// 1. While the leader is proven to be this child, the identities of its descendants are
959    ///    recorded (parent links; descendants that already outlived a parent that exited are
960    ///    not findable, as for [`descendant_identities`](Self::descendant_identities)).
961    /// 2. Unix: `SIGTERM` to the leader's whole process group (a detached child leads its own
962    ///    session, so that group is its own), up to `options.grace` for the group to leave,
963    ///    then `SIGKILL` to the group, all before the leader is reaped, so the group id cannot
964    ///    be recycled. Windows: the retained job if there is one (ordinary children), and the
965    ///    leader (`options.windows_exit_code`).
966    /// 3. The leader is reaped.
967    /// 4. The recorded descendants that are still the same process (pid and start time; a
968    ///    recycled pid is refused, never signalled) are swept, leaves first, with
969    ///    `options.grace`. This is what reaches a helper that left the group (a daemon that
970    ///    called `setsid`) and, on Windows, the descendants of a detached child.
971    ///
972    /// If another path already reaped the leader on Unix, nothing is signalled and the cached
973    /// status is returned with an empty sweep. No terminate-on-drop is implied: calling this
974    /// or not does not change what `Drop` does.
975    pub fn terminate_tree_deep(
976        &mut self,
977        options: TerminationOptions,
978    ) -> io::Result<TreeTermination> {
979        let mut found = self.descendant_identities()?;
980        found.reverse(); // leaves first
981        #[cfg(unix)]
982        if !self.tree_terminated {
983            signal_shared(&self.child, SignalTarget::Group, libc::SIGTERM)?;
984            await_tree_shared(&self.child, &self.handle, options.grace, true)?;
985            signal_shared(&self.child, SignalTarget::Group, libc::SIGKILL)?;
986            self.tree_terminated = true;
987        }
988        #[cfg(windows)]
989        self.force_kill(options.windows_exit_code)?;
990        let status = self.wait()?;
991        let descendants = crate::sweep(&found, options.grace)?;
992        Ok(TreeTermination {
993            status,
994            descendants,
995        })
996    }
997    fn start_termination(&mut self, options: TerminationOptions) -> io::Result<()> {
998        #[cfg(unix)]
999        if !self.tree_terminated {
1000            self.signal(libc::SIGTERM)?;
1001            // Stops waiting as soon as nothing but the exited, unreaped leader is left (or the
1002            // leader was reaped elsewhere, which ends signalling). The leader is not reaped
1003            // here: it must keep pinning the group id for the KILL below.
1004            self.await_tree(options.grace)?;
1005        }
1006        self.force_kill(options.windows_exit_code)
1007    }
1008    /// Waits, for at most `grace`, until the leader has exited and every other member of its
1009    /// group has too. The leader is observed without reaping it; then the group is listed
1010    /// every [`POLL_INTERVAL`](crate::exit_watch::POLL_INTERVAL) (the published 0.3.3 interval)
1011    /// until nothing but the leader is left. A group that cannot be listed is waited out for
1012    /// the rest of the grace in one timed sleep. Each listing takes the child lock briefly and
1013    /// releases it before the thread sleeps. Bounded by `grace` in every case.
1014    #[cfg(unix)]
1015    fn await_tree(&self, grace: Duration) -> io::Result<()> {
1016        // A detached child owns only its direct pid.
1017        await_tree_shared(&self.child, &self.handle, grace, !self.detached)
1018    }
1019    /// Sends `signal` to the group (or, for a detached child, to the leader alone) while the
1020    /// leader is unreaped and proven. Takes the child lock for each attempt and releases it
1021    /// between attempts.
1022    #[cfg(unix)]
1023    fn signal(&self, signal: i32) -> io::Result<()> {
1024        // Detached children only own their direct pid. Under the child's lock, and only while
1025        // the leader is unreaped, so the id cannot have been recycled.
1026        let target = if self.detached {
1027            SignalTarget::Leader
1028        } else {
1029            SignalTarget::Group
1030        };
1031        signal_shared(&self.child, target, signal).map(|_| ())
1032    }
1033    fn force_kill(&mut self, code: u32) -> io::Result<()> {
1034        if self.tree_terminated {
1035            return Ok(());
1036        }
1037        #[cfg(unix)]
1038        {
1039            let _ = code;
1040            self.signal(libc::SIGKILL)?;
1041        }
1042        #[cfg(windows)]
1043        crate::process_windows::terminate(&self.handle, self.job.as_deref(), code)?;
1044        self.tree_terminated = true;
1045        Ok(())
1046    }
1047}
1048impl OwnedChild {
1049    /// How long dropping this child waits for the killed leader to be reaped (default
1050    /// [`DEFAULT_DROP_REAP_TIMEOUT`]). `Drop` sends the kill at once and never waits longer than
1051    /// this: a leader that has not been reaped by then (it is in an uninterruptible state, for
1052    /// instance) is reaped later by a background thread on Unix, and on Windows the process
1053    /// handle is closed. `Duration::ZERO` means "do not wait". Does not affect
1054    /// [`terminate_tree`](Self::terminate_tree), which still waits for the reap.
1055    pub fn set_drop_reap_timeout(&mut self, timeout: Duration) -> &mut Self {
1056        self.drop_reap_timeout = timeout;
1057        self
1058    }
1059    /// The bound `Drop` applies to the reap.
1060    pub fn drop_reap_timeout(&self) -> Duration {
1061        self.drop_reap_timeout
1062    }
1063    /// Reaps the leader on a thread of its own, so an unbounded wait never blocks the caller.
1064    fn reap_in_background(&self) {
1065        #[cfg(unix)]
1066        if let Ok(reader) = self.handle.try_clone() {
1067            let _ = thread::Builder::new()
1068                .name("rightkit-drop-reap".into())
1069                .spawn(move || {
1070                    let _ = reader.wait();
1071                });
1072        }
1073    }
1074    /// Identities of this child's descendants (see [`crate::AdoptedIdentity::descendants`]), taken
1075    /// while the leader is proven to be this child. Empty once the leader has been reaped:
1076    /// its children are re-parented then and can no longer be found by their parent.
1077    pub fn descendant_identities(&self) -> io::Result<Vec<crate::AdoptedIdentity>> {
1078        let root = self.while_unreaped(|pid| match NonZeroU32::new(pid) {
1079            Some(pid) => crate::AdoptedIdentity::capture(pid),
1080            None => Ok(None),
1081        })?;
1082        match root {
1083            Some(Ok(Some(root))) => root.descendants(),
1084            Some(Err(error)) => Err(error),
1085            _ => Ok(Vec::new()),
1086        }
1087    }
1088}
1089impl Drop for OwnedChild {
1090    fn drop(&mut self) {
1091        // No longer owned: leave the registry before anything below can take long.
1092        crate::registry::forget(&self.child);
1093        if self.terminate_on_drop {
1094            // Bounded: the kill is sent at once, the reap is awaited for at most
1095            // `drop_reap_timeout`, and a child that has not been reaped by then is reaped by
1096            // a background thread. Dropping never waits on a process that will not die.
1097            if self.force_kill(1).is_ok() {
1098                drop(self.child().stdin.take());
1099                if !matches!(
1100                    self.handle.wait_timeout(self.drop_reap_timeout),
1101                    Ok(Some(_))
1102                ) {
1103                    self.reap_in_background();
1104                }
1105            }
1106        } else if self.detached {
1107            #[cfg(unix)]
1108            {
1109                // Shared launch still needs eventual reaping. Close owner pipes
1110                // now; the reaper thread makes non-blocking looks and releases the child
1111                // lock between them, so exit readers and kills are not held behind it.
1112                {
1113                    let mut child = self.child();
1114                    drop(child.stdin.take());
1115                    drop(child.stdout.take());
1116                    drop(child.stderr.take());
1117                }
1118                if let Ok(reader) = self.handle.try_clone() {
1119                    let _ = thread::Builder::new()
1120                        .name("rightkit-detached-reap".into())
1121                        .spawn(move || {
1122                            let _ = reader.wait();
1123                        });
1124                }
1125            }
1126        }
1127    }
1128}
1129
1130struct PartialChild {
1131    child: Option<OwnedChild>,
1132    timeout: Option<Duration>,
1133}
1134impl Drop for PartialChild {
1135    fn drop(&mut self) {
1136        if let Some(mut child) = self.child.take() {
1137            // Disable unbounded normal Drop before bounded cleanup.
1138            child.terminate_on_drop = false;
1139            let _ = child.force_kill(1);
1140            cleanup_direct(Arc::clone(&child.child), self.timeout);
1141        }
1142    }
1143}
1144/// How long a group signal that macOS refused with `EPERM` (the last members are mid-exit) is
1145/// retried before the refusal is reported.
1146#[cfg(unix)]
1147const MID_EXIT_RETRY: Duration = Duration::from_millis(300);
1148
1149/// One signal to a shared child's group or leader (see `OwnedChild::signal`), retrying for a
1150/// bounded time while macOS reports the last members mid-exit. The lock is taken for each
1151/// attempt and released between attempts. Returns the final outcome.
1152#[cfg(unix)]
1153pub(crate) fn signal_shared(
1154    shared: &Mutex<crate::unix_child::UnixChild>,
1155    target: SignalTarget,
1156    signal: i32,
1157) -> io::Result<SignalOutcome> {
1158    let started = Instant::now();
1159    loop {
1160        let (outcome, watch) = {
1161            let mut child = lock_child(shared);
1162            (child.signal(target, signal)?, child.exit_watch())
1163        };
1164        if outcome != SignalOutcome::MidExit {
1165            return Ok(outcome);
1166        }
1167        // macOS refused the group signal while its last members are mid-exit. The group is
1168        // gone once the exit completes: look again, for a bounded time, without the lock.
1169        let remaining = MID_EXIT_RETRY.saturating_sub(started.elapsed());
1170        if remaining.is_zero() {
1171            return Err(io::Error::from_raw_os_error(libc::EPERM));
1172        }
1173        watch.pause(remaining);
1174    }
1175}
1176
1177/// `OwnedChild::await_tree` over a shared child. `whole_group` false waits only for the leader.
1178#[cfg(unix)]
1179pub(crate) fn await_tree_shared(
1180    shared: &Mutex<crate::unix_child::UnixChild>,
1181    handle: &ProcessHandle,
1182    grace: Duration,
1183    whole_group: bool,
1184) -> io::Result<()> {
1185    use crate::{exit_watch::POLL_INTERVAL, unix_child::Members};
1186    let Some(deadline) = Instant::now().checked_add(grace) else {
1187        return Ok(());
1188    };
1189    let left = |deadline: Instant| deadline.saturating_duration_since(Instant::now());
1190    if !handle.wait_exited_timeout(left(deadline))? {
1191        return Ok(()); // the leader outlived the grace
1192    }
1193    if !whole_group {
1194        return Ok(());
1195    }
1196    loop {
1197        match lock_child(shared).group_other_members()? {
1198            Members::Pids(pids) if pids.is_empty() => return Ok(()),
1199            Members::Pids(_) => {}
1200            Members::Unknown => return wait_out(left(deadline)),
1201        }
1202        let remaining = left(deadline);
1203        if remaining.is_zero() {
1204            return Ok(()); // the grace is over
1205        }
1206        thread::sleep(POLL_INTERVAL.min(remaining));
1207    }
1208}
1209
1210/// The rest of a grace for a group that cannot be listed. There is nothing to look at, so this
1211/// is one timed sleep, not a loop.
1212#[cfg(unix)]
1213fn wait_out(remaining: Duration) -> io::Result<()> {
1214    thread::sleep(remaining);
1215    Ok(())
1216}
1217/// Stops and reaps a child whose spawn failed after the process existed. Every caller passes
1218/// an `Arc` that nothing but the spawning thread holds (the partial `OwnedChild`, from which no
1219/// `ProcessHandle` was cloned and which no caller has seen, or a child that was never wrapped),
1220/// so no other thread can contend for its lock. That is why the two blocking-under-lock waits
1221/// below, the unbounded one and the `rightkit-partial-reap` thread, cannot hold a deadline-
1222/// bearing caller back; both are what 0.3.3 did with `std::process::Child::wait`.
1223pub(crate) fn cleanup_direct(child: Arc<Mutex<PlatformChild>>, timeout: Option<Duration>) {
1224    let _ = lock_child(&child).kill();
1225    let Some(timeout) = timeout else {
1226        // Unbounded by default, as before. Exclusive child: see above.
1227        let _ = lock_child(&child).wait();
1228        return;
1229    };
1230    #[cfg(unix)]
1231    {
1232        // Non-blocking looks, each under the lock and released at once, until the child is
1233        // reaped or the timeout passes. A killed child is gone within one hint or interval.
1234        let watch = lock_child(&child).exit_watch();
1235        let deadline = Instant::now().checked_add(timeout);
1236        if matches!(
1237            watch.wait_for(deadline, || lock_child(&child).try_wait()),
1238            Ok(Some(_))
1239        ) {
1240            return;
1241        }
1242    }
1243    #[cfg(windows)]
1244    {
1245        let started = Instant::now();
1246        loop {
1247            match lock_child(&child).try_wait() {
1248                Ok(Some(_)) => return,
1249                Err(_) => break,
1250                Ok(None) => {}
1251            }
1252            if started.elapsed() >= timeout {
1253                break;
1254            }
1255            thread::sleep(Duration::from_millis(5).min(timeout.saturating_sub(started.elapsed())));
1256        }
1257    }
1258    // std Child does not reap on Drop. Transfer timed-out children to a waiter. This thread
1259    // holds the child's lock for the whole wait and is the only holder of the `Arc` (see
1260    // above), so nothing can queue behind it.
1261    let _ = thread::Builder::new()
1262        .name("rightkit-partial-reap".into())
1263        .spawn(move || {
1264            let _ = lock_child(&child).wait();
1265        });
1266}
1267
1268#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1269pub struct AdoptedProcess {
1270    pid: NonZeroU32,
1271}
1272impl AdoptedProcess {
1273    pub fn new(pid: NonZeroU32) -> Self {
1274        Self { pid }
1275    }
1276    pub fn id(&self) -> u32 {
1277        self.pid.get()
1278    }
1279    /// Whether a process with this pid is running. Unix: a zombie (exited, unreaped by its
1280    /// own parent) reads `false`. This is a bare-pid probe with no start-time check; use
1281    /// [`identity`](Self::identity) when the pid must still name a remembered process.
1282    pub fn is_running(&self) -> io::Result<bool> {
1283        process_is_running(self.pid)
1284    }
1285    /// The identity (start time and executable) of the process behind this pid now, for
1286    /// identity-checked signalling through [`AdoptedIdentity`](crate::AdoptedIdentity).
1287    /// `Ok(None)` when no process has the pid. Capture it only when the pid is known to name
1288    /// the intended process.
1289    pub fn identity(&self) -> io::Result<Option<crate::AdoptedIdentity>> {
1290        crate::AdoptedIdentity::capture(self.pid)
1291    }
1292}
1293#[cfg(test)]
1294fn spawn_for_test(
1295    command: Command,
1296    captured_pid: Arc<std::sync::atomic::AtomicU32>,
1297) -> io::Result<OwnedChild> {
1298    OwnedCommand::from_command(command).spawn_inner(false, true, Some(captured_pid))
1299}
1300
1301#[cfg(windows)]
1302fn process_is_running(pid: NonZeroU32) -> io::Result<bool> {
1303    use windows::Win32::{
1304        Foundation::{CloseHandle, ERROR_INVALID_PARAMETER, WAIT_TIMEOUT},
1305        System::Threading::{
1306            OpenProcess, WaitForSingleObject, PROCESS_QUERY_LIMITED_INFORMATION,
1307            PROCESS_SYNCHRONIZE,
1308        },
1309    };
1310
1311    let handle = unsafe {
1312        OpenProcess(
1313            PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE,
1314            false,
1315            pid.get(),
1316        )
1317    };
1318    let handle = match handle {
1319        Ok(handle) => handle,
1320        Err(error) => {
1321            if error.code() == ERROR_INVALID_PARAMETER.to_hresult() {
1322                return Ok(false);
1323            }
1324            return Err(io::Error::other(error.to_string()));
1325        }
1326    };
1327    let wait = unsafe { WaitForSingleObject(handle, 0) };
1328    let close = unsafe { CloseHandle(handle) };
1329    close.map_err(|error| io::Error::other(error.to_string()))?;
1330    match wait.0 {
1331        0 => Ok(false),
1332        value if value == WAIT_TIMEOUT.0 => Ok(true),
1333        _ => Err(io::Error::last_os_error()),
1334    }
1335}
1336
1337#[cfg(unix)]
1338fn process_is_running(pid: NonZeroU32) -> io::Result<bool> {
1339    let raw_pid = i32::try_from(pid.get()).map_err(io::Error::other)?;
1340    loop {
1341        // SAFETY: signal 0 performs only existence and permission checks; nothing is sent.
1342        if unsafe { libc::kill(raw_pid, 0) } == 0 {
1343            // Existence includes zombies: an exited process nobody reaped is dead, not
1344            // running (and is never reaped here - that is its parent's job).
1345            return Ok(!crate::foreign::process_is_zombie(pid.get()));
1346        }
1347        let error = io::Error::last_os_error();
1348        match error.raw_os_error() {
1349            Some(libc::EINTR) => continue,
1350            Some(libc::EPERM) => return Ok(!crate::foreign::process_is_zombie(pid.get())),
1351            Some(libc::ESRCH) => return Ok(false),
1352            _ => return Err(error),
1353        }
1354    }
1355}
1356
1357#[cfg(test)]
1358mod tests {
1359    #[test]
1360    fn option_defaults_preserve_existing_behavior() {
1361        let command = super::OwnedCommand::new("unused");
1362        assert_eq!(command.job_assignment, super::JobAssignmentMode::Strict);
1363        assert_eq!(
1364            command.unix_containment,
1365            super::UnixContainment::ProcessGroup
1366        );
1367        assert_eq!(command.partial_spawn_cleanup_timeout, None);
1368        assert_eq!(
1369            super::TerminationOptions::default().grace,
1370            std::time::Duration::ZERO
1371        );
1372        assert_eq!(super::TerminationOptions::default().windows_exit_code, 1);
1373    }
1374
1375    #[cfg(not(windows))]
1376    #[test]
1377    fn new_and_from_command_share_spawn_settings() {
1378        use super::OwnedCommand;
1379        use std::process::Command;
1380        // Debug covers every field. Off Windows nothing differs between the constructors.
1381        let by_new = OwnedCommand::new("unused");
1382        let by_from = OwnedCommand::from_command(Command::new("unused"));
1383        assert_eq!(format!("{by_new:?}"), format!("{by_from:?}"));
1384    }
1385
1386    /// Only `new` knows its Command's stdio and environment are std defaults. A wrapped
1387    /// Command may carry settings the crate cannot read, so `from_command` must not invent a
1388    /// default config: the allowlisted spawn then refuses instead of widening inheritance.
1389    #[cfg(windows)]
1390    #[test]
1391    fn only_new_supplies_a_default_windows_spawn_config() {
1392        use super::OwnedCommand;
1393        use std::process::Command;
1394        let by_new = OwnedCommand::new("unused");
1395        let by_from = OwnedCommand::from_command(Command::new("unused"));
1396        assert!(by_new.windows_spawn_config.is_some() && by_new.windows_spawn_config_auto);
1397        assert!(by_from.windows_spawn_config.is_none() && !by_from.windows_spawn_config_auto);
1398    }
1399
1400    #[test]
1401    fn process_priority_defaults_to_normal_and_keeps_the_requested_value() {
1402        use super::{OwnedCommand, ProcessPriority};
1403        let mut command = OwnedCommand::new("unused");
1404        assert_eq!(command.process_priority, ProcessPriority::Normal);
1405        command.process_priority(ProcessPriority::BelowNormal);
1406        assert_eq!(command.process_priority, ProcessPriority::BelowNormal);
1407        command.process_priority(ProcessPriority::Idle);
1408        assert_eq!(command.process_priority, ProcessPriority::Idle);
1409    }
1410
1411    /// Normal adds no nice change, so the default Unix spawn is unchanged. Lower priorities
1412    /// map to the documented floors.
1413    #[cfg(unix)]
1414    #[test]
1415    fn process_priority_maps_to_nice_floors() {
1416        use super::ProcessPriority;
1417        assert_eq!(ProcessPriority::Normal.nice_floor(), None);
1418        assert_eq!(ProcessPriority::BelowNormal.nice_floor(), Some(10));
1419        assert_eq!(ProcessPriority::Idle.nice_floor(), Some(19));
1420        assert_eq!(ProcessPriority::Efficient.nice_floor(), Some(10));
1421    }
1422
1423    /// A real child at `BelowNormal` reports the class Windows was asked for.
1424    #[cfg(windows)]
1425    #[test]
1426    fn below_normal_child_has_below_normal_priority_class() {
1427        use super::{OwnedCommand, ProcessPriority};
1428        use std::process::Stdio;
1429        use windows::Win32::{
1430            Foundation::CloseHandle,
1431            System::Threading::{
1432                GetPriorityClass, OpenProcess, BELOW_NORMAL_PRIORITY_CLASS,
1433                PROCESS_QUERY_LIMITED_INFORMATION,
1434            },
1435        };
1436        let mut command = OwnedCommand::new("ping");
1437        command
1438            .command_mut()
1439            .args(["-n", "6", "127.0.0.1"])
1440            .stdin(Stdio::null())
1441            .stdout(Stdio::null())
1442            .stderr(Stdio::null());
1443        command.process_priority(ProcessPriority::BelowNormal);
1444        let mut child = command.spawn().expect("spawn ping");
1445        // SAFETY: the handle is opened for this live child, queried once and closed.
1446        let class = unsafe {
1447            let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, child.id())
1448                .expect("open the child");
1449            let class = GetPriorityClass(handle);
1450            let _ = CloseHandle(handle);
1451            class
1452        };
1453        let _ = child.terminate_tree();
1454        assert_eq!(class, BELOW_NORMAL_PRIORITY_CLASS.0);
1455    }
1456
1457    /// A real child at `Idle` or `BelowNormal` runs with a nice value at or above the floor.
1458    #[cfg(unix)]
1459    #[test]
1460    fn lowered_priority_child_runs_at_or_above_the_nice_floor() {
1461        use super::{OwnedCommand, ProcessPriority};
1462        use std::{io::Read, process::Stdio};
1463        for (priority, floor) in [
1464            (ProcessPriority::BelowNormal, 10),
1465            (ProcessPriority::Idle, 19),
1466        ] {
1467            let mut command = OwnedCommand::new("/bin/sh");
1468            command
1469                .command_mut()
1470                .args(["-c", "ps -o ni= -p $$"])
1471                .stdin(Stdio::null())
1472                .stdout(Stdio::piped())
1473                .stderr(Stdio::null());
1474            command.process_priority(priority);
1475            let mut child = command.spawn().expect("spawn sh");
1476            let mut text = String::new();
1477            child
1478                .take_stdout()
1479                .expect("piped stdout")
1480                .read_to_string(&mut text)
1481                .expect("read ps output");
1482            let _ = child.wait();
1483            let nice: i32 = text.trim().parse().expect("ps printed a nice value");
1484            assert!(nice >= floor, "nice {nice} below floor {floor}");
1485        }
1486    }
1487
1488    #[test]
1489    fn breakaway_is_off_by_default_explicit_by_default_opt_in_and_silent_is_separate() {
1490        use super::BreakawayMode;
1491        let mut command = super::OwnedCommand::new("unused");
1492        assert_eq!(command.windows_breakaway, BreakawayMode::None);
1493        command.windows_allow_breakaway(true);
1494        assert_eq!(command.windows_breakaway, BreakawayMode::Explicit);
1495        command.windows_allow_silent_breakaway(true);
1496        assert_eq!(command.windows_breakaway, BreakawayMode::Silent);
1497        command.windows_allow_silent_breakaway(false);
1498        assert_eq!(command.windows_breakaway, BreakawayMode::None);
1499    }
1500
1501    #[test]
1502    fn kill_on_parent_exit_is_opt_in() {
1503        let mut command = super::OwnedCommand::new("unused");
1504        assert!(!command.kill_on_parent_exit);
1505        command.kill_on_parent_exit(true);
1506        assert!(command.kill_on_parent_exit);
1507    }
1508
1509    #[test]
1510    fn breakaway_denied_is_a_typed_recoverable_error() {
1511        let error =
1512            std::io::Error::new(std::io::ErrorKind::PermissionDenied, super::BreakawayDenied);
1513        assert!(error
1514            .get_ref()
1515            .and_then(|source| source.downcast_ref::<super::BreakawayDenied>())
1516            .is_some());
1517        assert!(super::BreakawayDenied.to_string().contains("breakaway"));
1518    }
1519
1520    #[test]
1521    fn a_strict_detached_spawn_passes_other_failures_through_untyped() {
1522        let command = super::OwnedCommand::new("rightkit-no-such-program-for-strict-detach");
1523        let Err(error) = command.spawn_uncontained_detached_strict() else {
1524            panic!("a missing program must not spawn");
1525        };
1526        assert!(error
1527            .get_ref()
1528            .and_then(|source| source.downcast_ref::<super::BreakawayDenied>())
1529            .is_none());
1530    }
1531
1532    #[test]
1533    fn a_strict_detached_spawn_still_rejects_kill_on_parent_exit() {
1534        let mut command = super::OwnedCommand::new("unused");
1535        command.kill_on_parent_exit(true);
1536        let Err(error) = command.spawn_uncontained_detached_strict() else {
1537            panic!("a detached spawn must not accept the parent-death tie");
1538        };
1539        assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
1540    }
1541
1542    #[test]
1543    fn a_detached_spawn_rejects_kill_on_parent_exit() {
1544        // Rejected before anything is started, so the program never needs to exist.
1545        let mut command = super::OwnedCommand::new("unused");
1546        command.kill_on_parent_exit(true);
1547        let Err(error) = command.spawn_uncontained_detached() else {
1548            panic!("a detached spawn must not accept the parent-death tie");
1549        };
1550        assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
1551    }
1552
1553    /// Hosts other than Linux and macOS have no parent-death primitive: the option fails closed,
1554    /// and the program is never started (it would create the marker file).
1555    #[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
1556    #[test]
1557    fn a_host_without_a_parent_death_primitive_refuses_before_starting_anything() {
1558        let marker =
1559            std::env::temp_dir().join(format!("rightkit-process-untied-{}", std::process::id()));
1560        let _ = std::fs::remove_file(&marker);
1561        let mut command = super::OwnedCommand::new("/usr/bin/touch");
1562        command.command_mut().arg(&marker);
1563        command.kill_on_parent_exit(true);
1564        let Err(error) = command.spawn() else {
1565            panic!("kill_on_parent_exit must not run the child untied");
1566        };
1567        assert_eq!(error.kind(), std::io::ErrorKind::Unsupported);
1568        std::thread::sleep(std::time::Duration::from_millis(200));
1569        assert!(!marker.exists(), "the program ran");
1570    }
1571
1572    #[test]
1573    fn option_builders_keep_every_requested_value() {
1574        use super::{JobAssignmentMode, OwnedCommand, TerminationOptions, UnixContainment};
1575        use std::time::Duration;
1576        let mut command = OwnedCommand::new("unused");
1577        command
1578            .job_assignment_mode(JobAssignmentMode::BestEffort)
1579            .unix_containment(UnixContainment::Session)
1580            .partial_spawn_cleanup_timeout(Duration::from_secs(5));
1581        assert_eq!(command.job_assignment, JobAssignmentMode::BestEffort);
1582        assert_eq!(command.unix_containment, UnixContainment::Session);
1583        assert_eq!(
1584            command.partial_spawn_cleanup_timeout,
1585            Some(Duration::from_secs(5))
1586        );
1587        let options = TerminationOptions::default()
1588            .with_grace(Duration::from_millis(100))
1589            .with_windows_exit_code(1067);
1590        assert_eq!(options.grace, Duration::from_millis(100));
1591        assert_eq!(options.windows_exit_code, 1067);
1592    }
1593
1594    #[test]
1595    fn zero_bound_partial_spawn_failure_still_reaps_the_child() {
1596        use std::{
1597            num::NonZeroU32,
1598            process::Command,
1599            sync::{
1600                atomic::{AtomicU32, Ordering},
1601                Arc,
1602            },
1603            thread,
1604            time::{Duration, Instant},
1605        };
1606        let command = if cfg!(windows) {
1607            let mut command = Command::new("powershell.exe");
1608            command.args([
1609                "-NoLogo",
1610                "-NoProfile",
1611                "-NonInteractive",
1612                "-Command",
1613                "Start-Sleep -Seconds 30",
1614            ]);
1615            command
1616        } else {
1617            let mut command = Command::new("/bin/sh");
1618            command.args(["-c", "exec sleep 30"]);
1619            command
1620        };
1621        let mut command = super::OwnedCommand::from_command(command);
1622        command.partial_spawn_cleanup_timeout(Duration::ZERO);
1623        let captured = Arc::new(AtomicU32::new(0));
1624        let started = Instant::now();
1625        assert!(command
1626            .spawn_inner(false, true, Some(Arc::clone(&captured)))
1627            .is_err());
1628        assert!(started.elapsed() < Duration::from_secs(3));
1629        let pid = captured.load(Ordering::SeqCst);
1630        assert_ne!(pid, 0);
1631        let process = super::AdoptedProcess::new(NonZeroU32::new(pid).unwrap());
1632        let started = Instant::now();
1633        while process.is_running().unwrap() {
1634            assert!(started.elapsed() < Duration::from_secs(5));
1635            thread::sleep(Duration::from_millis(5));
1636        }
1637    }
1638
1639    #[test]
1640    fn owned_commands_hide_their_console_window_by_default() {
1641        assert!(super::OwnedCommand::new("x").windows_hidden);
1642        assert!(super::OwnedCommand::from_command(std::process::Command::new("x")).windows_hidden);
1643    }
1644
1645    /// A kill-on-close job standing in for an in-process host's own job object.
1646    #[cfg(windows)]
1647    fn host_job() -> std::os::windows::io::OwnedHandle {
1648        use std::os::windows::io::FromRawHandle;
1649        use windows::Win32::System::JobObjects::{
1650            CreateJobObjectW, JobObjectExtendedLimitInformation, SetInformationJobObject,
1651            JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
1652        };
1653        let job = unsafe { CreateJobObjectW(None, None) }.unwrap();
1654        let job_handle = unsafe { std::os::windows::io::OwnedHandle::from_raw_handle(job.0 as _) };
1655        let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
1656        info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
1657        unsafe {
1658            SetInformationJobObject(
1659                job,
1660                JobObjectExtendedLimitInformation,
1661                &info as *const _ as *const _,
1662                std::mem::size_of_val(&info) as u32,
1663            )
1664        }
1665        .unwrap();
1666        job_handle
1667    }
1668
1669    #[cfg(windows)]
1670    fn in_job(pid: u32, job: &std::os::windows::io::OwnedHandle) -> bool {
1671        use std::os::windows::io::AsRawHandle;
1672        #[link(name = "kernel32")]
1673        unsafe extern "system" {
1674            fn OpenProcess(access: u32, inherit: i32, pid: u32) -> *mut std::ffi::c_void;
1675            fn IsProcessInJob(
1676                process: *mut std::ffi::c_void,
1677                job: *mut std::ffi::c_void,
1678                result: *mut i32,
1679            ) -> i32;
1680            fn CloseHandle(handle: *mut std::ffi::c_void) -> i32;
1681        }
1682        unsafe {
1683            let process = OpenProcess(0x1000, 0, pid); // PROCESS_QUERY_LIMITED_INFORMATION
1684            assert!(!process.is_null());
1685            let mut inside = 0;
1686            assert_ne!(
1687                IsProcessInJob(process, job.as_raw_handle() as _, &mut inside),
1688                0
1689            );
1690            CloseHandle(process);
1691            inside != 0
1692        }
1693    }
1694
1695    #[cfg(windows)]
1696    #[test]
1697    fn children_join_the_callers_job_and_die_when_the_caller_closes_it() {
1698        use std::os::windows::io::AsHandle;
1699        use std::time::{Duration, Instant};
1700        let job = host_job();
1701        let sleeper = || {
1702            let mut command = super::OwnedCommand::new("powershell.exe");
1703            command.command_mut().args([
1704                "-NoLogo",
1705                "-NoProfile",
1706                "-NonInteractive",
1707                "-Command",
1708                "Start-Sleep -Seconds 60",
1709            ]);
1710            command.windows_job(job.as_handle()).unwrap();
1711            command.spawn().unwrap()
1712        };
1713        // The second child joins a job that already holds a process: binding must happen
1714        // before RightKit's own jobs, or Windows refuses it.
1715        let (first, second) = (sleeper(), sleeper());
1716        let pids = [first.id(), second.id()];
1717        assert!(
1718            pids.iter().all(|pid| in_job(*pid, &job)),
1719            "children must be in the caller's job"
1720        );
1721
1722        // The caller closes its job while the owned children are still alive: they die.
1723        drop(job);
1724        let deadline = Instant::now() + Duration::from_secs(5);
1725        for pid in pids {
1726            let process = super::AdoptedProcess::new(std::num::NonZeroU32::new(pid).unwrap());
1727            while process.is_running().unwrap_or(false) {
1728                assert!(
1729                    Instant::now() < deadline,
1730                    "child {pid} survived its caller's job"
1731                );
1732                std::thread::sleep(Duration::from_millis(20));
1733            }
1734        }
1735        drop((first, second));
1736    }
1737
1738    #[test]
1739    fn a_failure_after_spawn_cleans_up_the_partially_wrapped_child() {
1740        use std::{
1741            process::Command,
1742            sync::{
1743                atomic::{AtomicU32, Ordering},
1744                Arc,
1745            },
1746            thread,
1747            time::{Duration, Instant},
1748        };
1749
1750        // A long-lived child that survives on its own if the partial-spawn cleanup fails.
1751        let command = if cfg!(windows) {
1752            // windowless: spawned through spawn_owned (CREATE_NO_WINDOW).
1753            let mut command = Command::new("powershell.exe");
1754            command.args([
1755                "-NoLogo",
1756                "-NoProfile",
1757                "-NonInteractive",
1758                "-Command",
1759                "Start-Sleep -Seconds 60",
1760            ]);
1761            command
1762        } else {
1763            // windowless: spawned through spawn_owned (CREATE_NO_WINDOW).
1764            let mut command = Command::new("sleep");
1765            command.arg("60");
1766            command
1767        };
1768        let spawned_pid = Arc::new(AtomicU32::new(0));
1769
1770        assert!(super::spawn_for_test(command, Arc::clone(&spawned_pid)).is_err());
1771        let pid = spawned_pid.load(Ordering::SeqCst);
1772        assert_ne!(pid, 0, "test must fail after the OS process was spawned");
1773        let process = super::AdoptedProcess::new(std::num::NonZeroU32::new(pid).unwrap());
1774        let deadline = Instant::now() + Duration::from_secs(5);
1775        while process.is_running().unwrap_or(false) {
1776            assert!(
1777                Instant::now() < deadline,
1778                "partially spawned process leaked"
1779            );
1780            thread::sleep(Duration::from_millis(20));
1781        }
1782    }
1783}