use std::os::unix::process::ExitStatusExt as _;
use std::process::Stdio;
use std::time::{Duration, Instant};
use rustix::process::{Pid, Signal as Raw, WaitId, WaitIdOptions, kill_process, waitid};
use super::Child;
use crate::Scope;
use crate::testing::sh;
fn reported(pid: Pid) -> bool {
let options = WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT;
waitid(WaitId::Pid(pid), options).unwrap().is_some()
}
fn within(limit: Duration, mut check: impl FnMut() -> bool) -> bool {
let deadline = Instant::now() + limit;
while !check() {
if Instant::now() > deadline {
return false;
}
std::thread::sleep(Duration::from_millis(5));
}
true
}
fn stopped(pid: Pid) -> bool {
let output = sh(&format!("ps -o stat= -p {}", pid.as_raw_nonzero()))
.output()
.unwrap();
output.stdout.starts_with(b"T")
}
#[test]
fn a_waiter_blocks_again_after_its_child_is_stopped_and_continued_and_still_sees_the_exit() {
let mut command = sh("read line; exit 4");
command.stdin(Stdio::piped());
let mut child = Child::spawn(command, Scope::Group).unwrap();
let pid = Pid::from_raw(child.id().try_into().unwrap()).unwrap();
let waiter = child.waiter();
let waiting = std::thread::spawn(move || waiter.wait());
kill_process(pid, Raw::STOP).unwrap();
assert!(within(Duration::from_secs(5), || stopped(pid)));
assert!(
within(Duration::from_secs(1), || !reported(pid)),
"the stop report stayed, so the waiter keeps waking"
);
kill_process(pid, Raw::CONT).unwrap();
assert!(
!waiting.is_finished(),
"the waiter returned before the exit"
);
drop(child.take_stdin());
waiting.join().unwrap().unwrap();
assert!(child.has_exited().unwrap());
assert_eq!(child.reap().unwrap().code(), Some(4));
}
#[test]
fn a_stopped_child_has_not_exited() {
let mut child = Child::spawn(sh("sleep 30"), Scope::Group).unwrap();
let pid = Pid::from_raw(child.id().try_into().unwrap()).unwrap();
kill_process(pid, Raw::STOP).unwrap();
assert!(within(Duration::from_secs(5), || stopped(pid)));
assert!(!child.has_exited().unwrap());
kill_process(pid, Raw::KILL).unwrap();
assert_eq!(child.reap().unwrap().signal(), Some(9));
}