use std::fs::{self, File, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process;
use std::time::SystemTime;
#[derive(Debug)]
pub struct PidFile {
path: PathBuf,
}
impl PidFile {
pub fn create(path: &Path) -> io::Result<Self> {
let mut f = File::create(path)?;
writeln!(f, "{}", std::process::id())?;
f.flush()?;
Ok(Self {
path: path.to_path_buf(),
})
}
pub fn touch(&self) -> io::Result<()> {
OpenOptions::new()
.write(true)
.open(&self.path)?
.set_modified(SystemTime::now())
}
}
impl Drop for PidFile {
fn drop(&mut self) {
let ours = fs::read_to_string(&self.path)
.ok()
.and_then(|s| s.trim().parse::<u32>().ok())
.is_some_and(|pid| pid == process::id());
if ours {
let _ = fs::remove_file(&self.path);
}
}
}