pub fn guard(name: &str) -> Result<Guard>guard only.Expand description
Starts the process guard with secure defaults: a single-instance lock in
the default lock directory for name, umask(0o027), and the soft
open-file limit raised to 65 536 (at least 1 024 required). Call it before
any file is opened and before threads start, and keep the Guard for the
life of the process.
The default lock directory depends only on the user the process runs as, never on environment variables, so a copy started by a service manager and one started from a shell find the same lock (D-106):
| Platform | root | other users |
|---|---|---|
| Linux | /run/<name> | <home>/.local/state/<name>/run |
| macOS | /var/run/<name> | <home>/Library/Application Support/<name>/run |
| FreeBSD | /var/run/<name> | <home>/.local/state/<name>/run |
| Windows | the user’s local application data folder, <name>\run | the same |
<home> is the home directory in the account database, not $HOME. The
lock is per user: copies running as different users do not exclude each
other. A program guarding shared data (a database) passes its data
directory with GuardBuilder::lock_dir, so every copy that could touch
the data finds the same lock.
use sys_lib as sys;
let guard = sys::process::guard("site")?; // before any file is opened
println!("lock {:?}", guard.lock_file());
// ... run; the lock is held while `guard` lives.§Errors
Error::AlreadyRunning when another copy holds the lock,
Error::RunDirUnavailable when the lock directory cannot be created or
trusted (or, for a user other than root, the account has no home
directory), Error::OpenFilesTooLow when the hard open-file limit is
below the minimum, and Error::InvalidInput for an invalid name.