qpidfile/lib.rs
1//! A simple representation of a "pidfile".
2//!
3//! Creates a pidfile on creation and automatically remove it on termination.
4//!
5//! ```
6//! fn main() {
7//! let pidfile = Pidfile::new("myserver.pid");
8//! // .. run server ..
9//!
10//! // On termination the Pidfile will automatically be removed.
11//! }
12//! ```
13//!
14//! Be mindful of the [`Drop`] trait caveats; for instance calling
15//! [`std::process::exit()`] will cause Drop traits not to run.
16//!
17//! [`std::process::exit()`]: https://doc.rust-lang.org/std/process/fn.exit.html
18//! [`Drop`]: https://doc.rust-lang.org/std/ops/trait.Drop.html
19use std::io::prelude::*;
20use std::path::{Path, PathBuf};
21use std::process;
22use std::fs::File;
23
24pub struct Pidfile {
25 fname: PathBuf
26}
27
28impl Drop for Pidfile {
29 fn drop(&mut self) {
30 if let Err(e) = std::fs::remove_file(&self.fname) {
31 eprintln!("Unable to remove pidfile {:?}; {}", self.fname, e);
32 }
33 }
34}
35
36/// Representation of a "pidfile", which contains the process identifier, of
37/// the current process, in ascii base-10 format.
38///
39/// A [`Drop`] trait is used to automatically remove the pidfile on
40/// termination.
41///
42/// [`Drop`]: https://doc.rust-lang.org/std/ops/trait.Drop.html
43impl Pidfile {
44 /// (Over)write the file specified in the parameter fname with the process
45 /// idenfier of the current process.
46 pub fn new<P: AsRef<Path>>(fname: P) -> std::io::Result<Self> {
47 let mut file = File::create(fname.as_ref())?;
48 let pidstr = format!("{}", process::id());
49 file.write_all(pidstr.as_bytes())?;
50 Ok(Pidfile { fname: fname.as_ref().to_path_buf() })
51 }
52}
53
54// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :