use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[non_exhaustive]
pub struct Owner {
pub pid: u32,
pub boot: String,
pub token: String,
}
impl Owner {
#[must_use]
pub fn this_process() -> Owner {
let mut bytes = [0u8; 8];
if getrandom::fill(&mut bytes).is_err() {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.subsec_nanos());
bytes = u64::from(nanos).to_le_bytes();
}
Owner {
pid: std::process::id(),
boot: this_boot(),
token: bytes
.iter()
.flat_map(|b| [b >> 4, b & 0x0f])
.map(|nibble| char::from_digit(u32::from(nibble), 16).unwrap_or('0'))
.collect(),
}
}
#[must_use]
pub fn is_alive(&self) -> bool {
if self.boot != this_boot() {
return false;
}
if self.pid == std::process::id() {
return true;
}
pid_alive(self.pid)
}
}
fn this_boot() -> String {
#[cfg(target_os = "linux")]
{
if let Ok(id) = std::fs::read_to_string("/proc/sys/kernel/random/boot_id") {
return id.trim().to_owned();
}
}
String::new()
}
#[cfg(unix)]
fn pid_alive(pid: u32) -> bool {
use nix::errno::Errno;
let Ok(raw) = i32::try_from(pid) else {
return false;
};
match nix::sys::signal::kill(nix::unistd::Pid::from_raw(raw), None) {
Ok(()) | Err(Errno::EPERM) => true,
Err(_) => false,
}
}
#[cfg(windows)]
fn pid_alive(pid: u32) -> bool {
crate::process::process_runs(pid)
}
#[cfg(not(any(unix, windows)))]
fn pid_alive(_pid: u32) -> bool {
true
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
#[test]
fn this_process_is_alive_and_a_holder_of_another_boot_or_a_gone_pid_isnt() {
let me = Owner::this_process();
assert!(me.is_alive());
assert_ne!(me.token, Owner::this_process().token, "a token per holder");
let mut other_boot = me.clone();
other_boot.boot = "another-boot".into();
other_boot.pid = 1;
assert!(!other_boot.is_alive());
let mut gone = me.clone();
gone.pid = dead_pid();
assert!(!gone.is_alive(), "a pid no process has (Windows: OpenProcess refuses it)");
}
#[test]
fn another_running_process_is_alive() {
let mut command = if cfg!(windows) {
let mut ping = std::process::Command::new("ping");
ping.args(["-n", "300", "127.0.0.1"]);
ping
} else {
let mut sleep = std::process::Command::new("sleep");
sleep.arg("300");
sleep
};
let running = isothrum_test_support::ChildGuard::spawn(command.stdout(std::process::Stdio::null())).unwrap();
let mut other = Owner::this_process();
other.pid = running.id();
assert!(other.is_alive());
}
pub(crate) fn dead_pid() -> u32 {
let mut command = if cfg!(windows) {
let mut cmd = std::process::Command::new("cmd");
cmd.args(["/C", "exit 0"]);
cmd
} else {
std::process::Command::new("true")
};
let mut child = command.spawn().unwrap();
let pid = child.id();
child.wait().unwrap();
pid
}
}