use std::os::fd::{AsRawFd, RawFd};
use super::proc_source::{Forgotten, Waited};
use crate::test_child::reaped_elsewhere::{reap_behind, reap_behind_status};
async fn holds_the_pidfd_after_forgetting_a_live_root_as(fate: Forgotten) -> bool {
crate::tokio::test_runtime::assert_current_thread();
let (mut child, writer) = super::root_state_tests::session_blocker(false);
let pid = child.pid();
assert!(child.root_pidfd().is_some(), "a spawned handle holds its root's pidfd");
child.proc_mut().forget_as("was forgotten by a test", fate);
let held = child.root_pidfd().is_some();
drop(writer);
reap_behind(pid);
held
}
#[skuld::test]
async fn an_unproven_forget_keeps_the_pidfd() {
assert!(
holds_the_pidfd_after_forgetting_a_live_root_as(Forgotten::Unproven).await,
"the pidfd names the root exactly whatever a peek said"
);
}
#[skuld::test]
async fn a_forget_as_reaped_elsewhere_keeps_the_pidfd() {
assert!(
holds_the_pidfd_after_forgetting_a_live_root_as(Forgotten::ReapedElsewhere).await,
"the root's group is still decided through its pidfd"
);
}
fn reaped_elsewhere_root() -> (crate::tokio::Child, RawFd) {
let (mut child, writer) = super::root_state_tests::session_blocker(false);
let fd = child
.root_pidfd()
.expect("a spawned handle holds its root's pidfd")
.as_raw_fd();
child.kill().expect("kill the root");
drop(writer);
crate::test_child::assert_killed("the root", reap_behind_status(child.pid()));
(child, fd)
}
fn pidfd_after(child: &mut crate::tokio::Child, forget: impl FnOnce(&mut super::ProcSource) -> bool) -> RawFd {
assert!(forget(child.proc_mut()), "the forget forgot tokio's `Child`");
child.root_pidfd().expect("the forget kept the pidfd").as_raw_fd()
}
#[skuld::test]
async fn a_forget_for_a_drop_keeps_the_pidfd() {
crate::tokio::test_runtime::assert_current_thread();
let (mut child, fd) = reaped_elsewhere_root();
let view = child.read_root_view(crate::containment::dispatch::TeardownCaller::Drop);
assert_eq!(pidfd_after(&mut child, |proc| proc.forget_for(&view).is_some()), fd);
}
#[skuld::test]
async fn a_forget_for_a_wait_keeps_the_pidfd() {
crate::tokio::test_runtime::assert_current_thread();
for waited in [Waited::Foreign, Waited::Unverified] {
let (mut child, fd) = reaped_elsewhere_root();
assert_eq!(
pidfd_after(&mut child, |proc| proc.forget_for_wait(waited, None).is_some()),
fd,
"{waited:?}"
);
}
}
#[skuld::test]
async fn the_forget_moves_the_pidfd_and_the_handle_closes_it() {
crate::tokio::test_runtime::assert_current_thread();
let (mut child, fd) = reaped_elsewhere_root();
child.try_wait().expect_err("a foreign reap answers ECHILD");
assert_eq!(
child.root_pidfd().expect("the forget kept the pidfd").as_raw_fd(),
fd,
"the same fd, not a duplicate"
);
drop(child);
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
let err = std::io::Error::last_os_error();
assert_eq!(
(flags, err.raw_os_error()),
(-1, Some(libc::EBADF)),
"the handle's drop closed the pidfd"
);
}