Problem
Naive PID-file locks check-then-write — two processes starting microseconds apart both believe they won.
Approach
Atomic cross-process PID-file lock (~400 LOC, minimal deps, Rust 1.70+). Dead holders detected via liveness probe with safe takeover; RAII release on drop plus explicit release(); same-process reentrancy honestly documented as out of scope (use Mutex); integration test spawns real children to prove exactly-one-winner under a concurrent race.
Code
From src/lock.rs — the contract is in the type docs:
/// An atomic cross-process PID-file lock.
///
/// Construct via [`FileLock::acquire`] or [`FileLock::acquire_with_identity`].
/// The lock releases automatically when this value is dropped; you can
/// also call [`FileLock::release`] explicitly.
///
/// This is a cross-PROCESS lock. Two `FileLock` values on the same path
/// inside ONE Rust process will both succeed — they share the same PID
/// so the lock can't distinguish them.
pub struct FileLock {
path: PathBuf,
owner_pid: u32,
active: bool,
}
Preview
Run cargo test, including test_exactly_one_winner_under_concurrent_race with real spawned children. Honest scope from the README: one machine, local filesystem, fail-fast — not distributed, not async, not kernel-enforced.
Results
Microsecond races resolve to exactly one winner; crashed holders hand over safely instead of deadlocking the next cycle.
Links
- Code: https://github.com/dnarsh/racefree-filelock-rs
- Used by: /projects/evergreen-watchdog