use core::sync::atomic::AtomicU32;
use core::time::Duration;
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Process {
pub pid: u32,
pub start: u64,
}
const STATE_FIELD: usize = 0;
const START_FIELD: usize = 19;
impl Process {
pub fn current() -> Self {
let pid = std::process::id();
Self { pid, start: Self::stat(pid).map_or(0, |(_, start)| start) }
}
#[cfg(not(miri))]
fn stat(pid: u32) -> Option<(char, u64)> {
let text = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
let rest = &text[text.rfind(')')? + 1..];
let fields: Vec<&str> = rest.split_whitespace().collect();
Some((fields.get(STATE_FIELD)?.chars().next()?, fields.get(START_FIELD)?.parse().ok()?))
}
#[cfg(miri)]
fn stat(_: u32) -> Option<(char, u64)> {
None
}
pub fn alive(self) -> bool {
if self.start == 0 || cfg!(miri) {
return true;
}
Self::stat(self.pid).is_some_and(|(state, start)| start == self.start && !matches!(state, 'Z' | 'X'))
}
}
pub trait FutexWord {
fn wait(&self, expected: u32, timeout: Duration);
fn wake_all(&self);
}
#[cfg(not(miri))]
impl FutexWord for AtomicU32 {
fn wait(&self, expected: u32, timeout: Duration) {
let ts = libc::timespec {
tv_sec: libc::time_t::try_from(timeout.as_secs()).unwrap_or(libc::time_t::MAX),
tv_nsec: timeout.subsec_nanos().into(),
};
unsafe { libc::syscall(libc::SYS_futex, self.as_ptr(), libc::FUTEX_WAIT, expected, &raw const ts) };
}
fn wake_all(&self) {
unsafe { libc::syscall(libc::SYS_futex, self.as_ptr(), libc::FUTEX_WAKE, i32::MAX) };
}
}
#[cfg(miri)]
impl FutexWord for AtomicU32 {
fn wait(&self, _: u32, _: Duration) {
std::thread::yield_now();
}
fn wake_all(&self) {}
}