use std::io::Read;
use std::os::unix::process::ExitStatusExt;
use std::process::{ChildStdin, ChildStdout, Command, Stdio};
use super::StdChild;
use crate::send_log::Capture;
pub(crate) struct BlockedTree {
pub(crate) root: StdChild,
pub(crate) grandchild: u32,
grandchild_stdin: ChildStdin,
stdout: ChildStdout,
}
pub(crate) fn blocked_tree() -> BlockedTree {
let mut root = StdChild::spawn(
crate::test_reexec::command(std::env::current_exe().expect("current_exe"))
.args(super::blocked_tree_root::argv())
.stdin(Stdio::piped())
.stdout(Stdio::piped()),
);
let grandchild_stdin = root.stdin.take().expect("piped stdin");
let mut stdout = root.stdout.take().expect("piped stdout");
let mut line = Vec::new();
loop {
let mut byte = [0u8; 1];
stdout.read_exact(&mut byte).expect("the grandchild's pid");
if byte[0] == b'\n' {
break;
}
line.push(byte[0]);
}
let grandchild = String::from_utf8(line)
.expect("utf-8")
.parse()
.expect("the grandchild's pid");
BlockedTree {
root,
grandchild,
grandchild_stdin,
stdout,
}
}
pub(crate) fn assert_tree_sigtermed(sends: &Capture, root: u32, grandchild: u32) {
assert_eq!(
sends.by_identity(),
[(root, libc::SIGTERM), (grandchild, libc::SIGTERM)],
"the walk must SIGTERM the root {root}, then its grandchild {grandchild}"
);
}
impl BlockedTree {
pub(crate) fn assert_died_of_sigterm(self) {
let Self {
mut root,
grandchild_stdin,
mut stdout,
..
} = self;
drop(grandchild_stdin);
let status = root.wait().expect("reap the root");
assert_eq!(status.signal(), Some(libc::SIGTERM), "root: got {status:?}");
let mut reported = String::new();
stdout
.read_to_string(&mut reported)
.expect("read to the end of the tree's stdout");
assert_eq!(
reported.trim(),
(128 + libc::SIGTERM).to_string(),
"the grandchild's reported status: 128 + the signal it died of"
);
}
}
pub(crate) struct SurvivorTree {
pub(crate) child: StdChild,
_stdout: ChildStdout,
pub(crate) process: crate::Process,
pub(crate) members: Vec<crate::identity::ProcessId>,
}
pub(crate) fn survivor_tree() -> SurvivorTree {
tree_of(super::TERM_SURVIVOR_TREE_ARGV)
}
pub(crate) fn tree_of(argv: &[&str]) -> SurvivorTree {
let mut child = StdChild::spawn(
Command::new(argv[0])
.args(&argv[1..])
.stdin(Stdio::piped())
.stdout(Stdio::piped()),
);
let mut stdout = child.stdout.take().expect("piped stdout");
let mut ready = [0u8; 2];
stdout.read_exact(&mut ready).expect("the readiness line");
let process = crate::Process::open_pid(child.id()).expect("open").expect("running");
let members = process
.id()
.children(crate::Recursive::Yes)
.expect("the root's descendants");
assert!(!members.is_empty(), "the subshell is a descendant of the root");
SurvivorTree {
child,
_stdout: stdout,
process,
members,
}
}