use std::path::{Path, PathBuf}; use std::fs; pub struct SessionLock { path: PathBuf, pid: u32, } impl SessionLock { pub fn new(session_dir: &Path) -> Self { SessionLock { path: session_dir.join(".lock"), pid: std::process::id(), } } pub fn try_lock(&self) -> std::io::Result { if self.path.exists() { let content = fs::read_to_string(&self.path).unwrap_or_default(); if let Ok(pid) = content.trim().parse::() { if self.is_alive(pid) { return Ok(false); } } } fs::write(&self.path, self.pid.to_string())?; Ok(true) } pub fn unlock(&self) { let _ = fs::remove_file(&self.path); } fn is_alive(&self, pid: u32) -> bool { unsafe { libc::kill(pid as i32, 0) == 0 } } } impl Drop for SessionLock { fn drop(&mut self) { let _ = fs::remove_file(&self.path); } }