//! Unix: the child leads a new process group, and a watchdog kills that //! group when Lutra's end of a pipe closes. //! //! The watchdog is `/bin/sh` reading its standard input, a pipe whose //! write end only the [`Group`] holds (standard library pipes are //! close-on-exec, so no other child inherits it). `read` returns at end of //! file, which happens when the [`Group`] drops the pipe or when Lutra's //! process ends for any reason, including `SIGKILL`; the watchdog then //! sends `SIGKILL` to the group. It runs in a process group of its own, so //! a Ctrl-C or hangup aimed at Lutra's group does not take it down first. use std::io; use std::os::unix::process::CommandExt; use std::process::{ChildStdin, Command, Stdio}; /// The watchdog script: wait for end of file on stdin, then kill the /// process group given as `$1`. const WATCHDOG: &str = "read -r _; kill -KILL -\"$1\" 2>/dev/null"; /// The child's process group and its watchdog. pub(crate) struct Group { /// The watchdog process, reaped after it has killed the group. watchdog: std::process::Child, /// Lutra's end of the watchdog's pipe; dropping it fires the watchdog. trigger: Option, } impl Group { /// Makes the child the leader of a new process group. pub(crate) fn prepare(command: &mut Command) { command.process_group(0); } /// Starts the watchdog for the group led by `child`. /// /// # Errors /// The error of starting `/bin/sh`, or a missing stdin pipe. pub(crate) fn attach(child: &std::process::Child) -> io::Result { let mut watchdog = Command::new("/bin/sh") .arg("-c") .arg(WATCHDOG) .arg("lutra-proc-watchdog") .arg(child.id().to_string()) .stdin(Stdio::piped()) .stdout(Stdio::null()) .stderr(Stdio::null()) .process_group(0) .spawn()?; let Some(trigger) = watchdog.stdin.take() else { let _ = watchdog.kill(); let _ = watchdog.wait(); return Err(io::Error::other("the watchdog has no stdin pipe")); }; Ok(Self { watchdog, trigger: Some(trigger), }) } /// Fires the watchdog and waits until it has killed the group. The /// results are ignored on purpose: a watchdog that is gone already has /// nothing left to do, and the caller kills the direct child itself. pub(crate) fn kill(&mut self) { if self.trigger.take().is_some() { let _ = self.watchdog.wait(); } } }