//! Child processes that die with Lutra (layer L0). //! //! [`spawn`] starts a [`std::process::Command`] inside a group that the //! operating system tears down when Lutra's process ends, even when Lutra //! is killed hard, and returns a [`Child`] whose [`Child::kill`] and //! [`Drop`] take the whole group (the child and everything it started). //! Phpactor uses it now; git, `php -l` and other tools use it next. //! //! - **Windows:** every child gets its own job object with //! `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`. Lutra holds the only handle, so //! the job closes, and kills its processes, when the [`Child`] is dropped //! or when Lutra's process ends in any way (the kernel closes its //! handles). Jobs nest (Windows 8 and later), so this works when Lutra //! itself runs inside a job (a terminal, `cargo`, a CI runner). //! Processes the child starts are in the job too. //! - **Unix:** the child leads a new process group. A watchdog //! (`/bin/sh`, in its own process group) blocks on a pipe whose write end //! only Lutra holds; when the pipe closes, because the [`Child`] is //! dropped or killed, because Lutra quits, or because Lutra is killed //! with `SIGKILL`, it sends `SIGKILL` to the child's group. What a //! `SIGKILL` of Lutra can still leave behind: processes that left the //! group themselves (`setsid`, `setpgid`, i.e. daemons), and the child if //! Lutra dies in the microseconds between starting it and starting its //! watchdog. If the watchdog itself is killed, the group is only killed //! by an explicit [`Child::kill`] or drop, which then signal the direct //! child only. //! //! A child starts running before it is put into its job (Windows) or before //! its watchdog exists (Unix), so a grandchild it starts in that window //! (microseconds) can escape; language servers and git start their own //! children much later. use std::io; use std::ops::{Deref, DerefMut}; use std::process::{Command, ExitStatus}; #[cfg(unix)] mod unix; #[cfg(windows)] mod windows; #[cfg(unix)] use unix::Group; #[cfg(windows)] use windows::Group; /// The group a child runs in on platforms without job objects or process /// groups: nothing beyond the child itself. #[cfg(not(any(unix, windows)))] struct Group; #[cfg(not(any(unix, windows)))] impl Group { /// Nothing to set up. fn prepare(_command: &mut Command) {} /// Nothing to attach. /// /// # Errors /// Never. fn attach(_child: &std::process::Child) -> io::Result { Ok(Self) } /// Nothing to kill beyond the child, which [`Child::kill`] handles. fn kill(&mut self) {} } /// A child process in its own kill-on-close group. /// /// It dereferences to [`std::process::Child`] for the pipes, `id`, /// `try_wait` and `wait`. [`Child::kill`] replaces the standard `kill` and /// takes the whole group. Dropping it kills the group and reaps the child, /// so a [`Child`] must be kept for as long as the process should run. pub struct Child { /// The process itself. inner: std::process::Child, /// Its job object (Windows) or watchdog (Unix). group: Group, } /// Starts `command` in a new kill-on-close group (see the crate docs). /// /// Everything else about `command` (arguments, environment, working /// directory, stdio, Windows creation flags) is used as given. /// /// # Errors /// The error of [`Command::spawn`], or the error of setting up the group /// (Windows: creating the job or assigning the process to it; Unix: /// starting the watchdog). When the group cannot be set up, the child that /// was already started is killed and reaped before the error is returned, /// so it never runs unguarded. pub fn spawn(mut command: Command) -> io::Result { Group::prepare(&mut command); let mut inner = command.spawn()?; match Group::attach(&inner) { Ok(group) => Ok(Child { inner, group }), Err(error) => { let _ = inner.kill(); let _ = inner.wait(); Err(error) } } } impl Child { /// Kills the child and every process in its group, without waiting for /// the child; call [`std::process::Child::wait`] to reap it. /// /// Killing a child that has exited already is not an error. /// /// # Errors /// The error of killing the direct child, as /// [`std::process::Child::kill`] reports it. Failing to reach the rest /// of the group is not reported: the job (Windows) or watchdog (Unix) /// is the only handle on it, and it is consumed either way. pub fn kill(&mut self) -> io::Result<()> { self.group.kill(); self.inner.kill() } /// Kills the group (see [`Child::kill`]) and waits for the child. /// /// # Errors /// The error of [`std::process::Child::wait`]. pub fn kill_and_wait(&mut self) -> io::Result { let _ = self.kill(); self.inner.wait() } } impl Deref for Child { type Target = std::process::Child; fn deref(&self) -> &Self::Target { &self.inner } } impl DerefMut for Child { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } impl std::fmt::Debug for Child { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Child") .field("id", &self.inner.id()) .finish_non_exhaustive() } } impl Drop for Child { /// Kills the group and reaps the child. Errors are ignored on purpose: /// the process may have exited already, and a destructor has no one to /// report to. fn drop(&mut self) { let _ = self.kill_and_wait(); } }