Struct pidfile_rs::Pidfile [−][src]
pub struct Pidfile { /* fields omitted */ }
Expand description
A PID file protected with a lock.
An instance of Pidfile
can be used to manage a PID file: create it,
lock it, detect already running daemons. It is backed by pidfile
functions of libbsd
/libutil
which use flopen
to lock the PID
file.
When a PID file is created, the process ID of the current process is not written there, making it possible to lock the PID file before forking and only write the ID of the forked process when it is ready.
The PID file is deleted automatically when the Pidfile
comes out of
the scope. To close the PID file without deleting it, for example, in
the parent process of a forked daemon, call close()
.
Example
When the parent process exits without calling destructors, e.g. by
using exit
or when forking with daemon
(3), Pidfile
can
be used in the following way:
// This example uses daemon(3) wrapped by nix to daemonise:
use nix::unistd::daemon;
use pidfile_rs::Pidfile;
// ...
let pidfile = Some(Pidfile::new(
&pidfile_path,
Permissions::from_mode(0o600)
)?);
// do some pre-fork preparations
// ...
// in the parent process, the PID file is closed without deleting it
daemon(false, true)?;
pidfile.unwrap().write();
// do some work
println!("The daemon’s work is done, now it’s time to go home.");
// the PID file will be deleted when this function returns
Implementations
Creates a new PID file and locks it.
If the PID file cannot be locked, returns PidfileError::AlreadyRunning
with
a PID of the already running process, or None
if no PID has been written to
the PID file yet.
Writes the current process ID to the PID file.
The file is truncated before writing.