sdlan-lib-rs/src/utils/pid_recorder.rs
2025-09-30 11:31:05 +08:00

40 lines
966 B
Rust
Executable File

use std::{
fs::{self, OpenOptions},
io::Write,
};
use tracing::{debug, error};
pub struct PidRecorder(String);
impl PidRecorder {
pub fn new(pidfile: &str) -> Self {
let pid = std::process::id();
match OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(pidfile)
{
Ok(mut fp) => {
fp.write(format!("{}", pid).as_bytes())
.expect("failed to write");
}
Err(e) => {
error!("failed to open pid file: {}", e);
// eprintln!("failed to open pid file: {}", e);
}
}
Self(pidfile.to_owned())
}
}
impl Drop for PidRecorder {
fn drop(&mut self) {
if let Err(e) = fs::remove_file(&self.0) {
error!("failed to remove pid file: {}", e);
// eprintln!("failed to remove pid file: {}", e);
}
}
}