Lines
97.06 %
Functions
66.67 %
Branches
100 %
//! A command run in its own process group so a termination signal reaches all of it.
use std::os::unix::process::CommandExt;
use std::process::{Child, Command, ExitStatus, Stdio};
use std::time::Duration;
use anyhow::{Context, Result, bail};
use super::group::{Group, Termination};
const POLL: Duration = Duration::from_millis(100);
/// Runs a command with inherited stdio to completion, with no stall budget.
///
/// On SIGHUP, SIGINT, SIGQUIT or SIGTERM the group is killed and an error returned, so the
/// caller unwinds and drops whatever it holds, such as a Postgres cluster.
/// `termination` is watched by the caller from before it acquired that state.
/// The group is a background one on the terminal, so stdin is closed:
/// interactive commands are not supported.
pub fn run_supervised(
program: &str,
args: &[String],
env: &[(&str, &str)],
termination: &Termination,
) -> Result<()> {
if termination.requested() {
bail!("{program} not started: a termination signal arrived first");
}
let mut child = Command::new(program)
.args(args)
.envs(env.iter().copied())
.stdin(Stdio::null())
.process_group(0)
.spawn()
.with_context(|| format!("failed to run {program}"))?;
let group = Group::of(&child);
let outcome = wait(&mut child, termination);
group.kill();
let _ = child.wait();
match outcome? {
Some(status) if status.success() => Ok(()),
Some(status) => bail!("{program} {} exited with {status}", args.join(" ")),
None => bail!("{program} interrupted by a termination signal"),
fn wait(child: &mut Child, termination: &Termination) -> Result<Option<ExitStatus>> {
loop {
if let Some(status) = child.try_wait().context("waiting on the child")? {
return Ok(Some(status));
return Ok(None);
std::thread::sleep(POLL);