use std::ffi::OsString;
use std::io::{Read as _, Write as _};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicU32, Ordering};
const FLAG: &str = "--cosca-zombie-leader-root";
static LEADER_TID: AtomicU32 = AtomicU32::new(0);
fn wait_for_the_leader_to_exit() {
loop {
let tid = LEADER_TID.load(Ordering::SeqCst);
if tid == 0 {
return;
}
unsafe {
libc::syscall(
libc::SYS_futex,
LEADER_TID.as_ptr(),
libc::FUTEX_WAIT,
tid,
std::ptr::null::<libc::timespec>(),
)
};
}
}
pub(crate) fn run_if_requested() {
let args: Vec<OsString> = std::env::args_os().collect();
if args.get(1).is_none_or(|a| a != FLAG) {
return;
}
run();
}
pub(crate) fn argv() -> [&'static str; 1] {
[FLAG]
}
fn run() -> ! {
#[allow(
clippy::disallowed_methods,
reason = "this process is single-threaded: nothing else forks, so there is no lock to hold"
)]
let cat = Command::new("cat")
.stdin(Stdio::inherit())
.stdout(Stdio::null())
.spawn()
.expect("spawn the cat");
let mut out = std::io::stdout().lock();
writeln!(out, "{}", cat.id()).expect("report the cat's pid");
out.flush().expect("report the cat's pid");
drop(out);
let tid = unsafe { libc::syscall(libc::SYS_set_tid_address, LEADER_TID.as_ptr()) };
LEADER_TID.store(u32::try_from(tid).expect("a thread's tid"), Ordering::SeqCst);
let blocked = std::thread::spawn(|| {
wait_for_the_leader_to_exit();
let mut out = std::io::stdout().lock();
writeln!(out, "exited").expect("report the leader's exit");
out.flush().expect("report the leader's exit");
drop(out);
_ = std::io::stdin().read(&mut [0u8; 1]);
});
std::mem::forget((cat, blocked));
unsafe { libc::syscall(libc::SYS_exit, 0) };
unreachable!("SYS_exit does not return");
}