| Crates.io | pidlock |
| lib.rs | pidlock |
| version | 0.2.1 |
| created_at | 2018-05-19 02:05:37.050743+00 |
| updated_at | 2025-09-07 19:35:21.164984+00 |
| description | A library for using pidfiles as resource locks |
| homepage | |
| repository | https://github.com/rockstar/pidlock |
| max_upload_size | |
| id | 66080 |
| size | 85,985 |
A library for creating and managing PID-based file locks, providing a simple and reliable way to ensure only one instance of a program runs at a time.
Pidlock is droppedAdd this to your Cargo.toml:
[dependencies]
pidlock = "0.2"
use pidlock::Pidlock;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create a new lock
let mut lock = Pidlock::new_validated("/run/lock/my_app.pid")?;
// Try to acquire the lock
match lock.acquire() {
Ok(()) => {
println!("Lock acquired successfully!");
// Do your work here...
// Explicitly release the lock (optional - it's auto-released on drop)
lock.release()?;
}
Err(pidlock::PidlockError::LockExists) => {
println!("Another instance is already running");
std::process::exit(1);
}
Err(e) => {
eprintln!("Failed to acquire lock: {}", e);
std::process::exit(1);
}
}
Ok(())
}
use pidlock::Pidlock;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let lock = Pidlock::new_validated("/run/lock/my_app.pid")?;
// Check if a lock file exists
if lock.exists() {
// Check if the lock is held by an active process
match lock.is_active()? {
true => println!("Lock is held by an active process"),
false => println!("Lock file exists but process is dead (stale lock)"),
}
} else {
println!("No lock file exists");
}
Ok(())
}
use pidlock::{Pidlock, PidlockError, InvalidPathError};
fn main() {
let result = Pidlock::new_validated("invalid<path>");
match result {
Ok(_) => println!("Path is valid"),
Err(PidlockError::InvalidPath(InvalidPathError::ProblematicCharacter { character, filename })) => {
println!("Invalid character '{}' in filename: {}", character, filename);
}
Err(e) => println!("Other error: {}", e),
}
}
use pidlock::Pidlock;
fn main() -> Result<(), Box<dyn std::error::Error>> {
{
let mut lock = Pidlock::new_validated("/run/lock/my_app.pid")?;
lock.acquire()?;
// Do work here...
// Lock is automatically released when it goes out of scope
}
// Lock file is now cleaned up
Ok(())
}
If you're upgrading from version 0.1.x:
Pidlock::new() with Pidlock::new_validated() for better error handlingResult type returned by new_validated()// Old (0.1.x)
let mut lock = pidlock::Pidlock::new("/path/to/pidfile.pid");
// New (0.2.x)
let mut lock = pidlock::Pidlock::new_validated("/path/to/pidfile.pid")?;
This library uses unsafe code for platform-specific process detection, but all unsafe operations are carefully validated and documented. The library ensures that:
pidlock is licensed under the MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)