#lock-files #raii #mutex #flock

fmutex

Cross-platform mutual exclusion across processes on a file or path

3 unstable releases

0.2.1 Mar 10, 2025
0.2.0 Mar 8, 2025
0.1.0 Feb 9, 2022

#152 in Filesystem

Download history 96/week @ 2024-12-13 332/week @ 2024-12-20 211/week @ 2024-12-27 281/week @ 2025-01-03 685/week @ 2025-01-10 476/week @ 2025-01-17 663/week @ 2025-01-24 537/week @ 2025-01-31 648/week @ 2025-02-07 770/week @ 2025-02-14 731/week @ 2025-02-21 611/week @ 2025-02-28 844/week @ 2025-03-07 592/week @ 2025-03-14 467/week @ 2025-03-21 456/week @ 2025-03-28

2,586 downloads per month
Used in 4 crates (3 directly)

MIT/Apache

17KB
229 lines

fmutex

Crates.io Version Docs.rs Latest Build Status

Mutual exclusion across processes on a file descriptor or path.

  • On Unix-like systems this is implemented use flock(2).
  • On Windows this is implemented using LockFileEx.

🚀 Getting started

First fmutex to your Cargo manifest.

cargo add fmutex

Now use one of the provided functions to lock a file descriptor (Unix) or handle (Windows) or a file path.

  • lock() to acquire a lock on a file descriptor or handle.
  • try_lock() to attempt to acquire a lock on a file descriptor or handle.
  • lock_path() to acquire a lock on a file path.
  • try_lock_path() to attempt to acquire a lock on a file path.

🤸 Usage

lock()

let fd = fs::OpenOptions::new().create(true).write(true).open(&path)?;

{
    let _guard = fmutex::lock(&fd)?;

    // do mutually exclusive stuff here

} // <-- `_guard` dropped here and the lock is released

try_lock()

let fd = fs::OpenOptions::new().create(true).write(true).open(&path)?;

match fmutex::try_lock(&fd)? {
    Some(_guard) => {

        // do mutually exclusive stuff here

    } // <-- `_guard` dropped here and the lock is released

    None => {
        eprintln!("the lock could not be acquired!");
    }
}

lock_path()

let path = "path/to/my/file.txt";

{
    let _guard = fmutex::lock_path(path)?;

    // do mutually exclusive stuff here

} // <-- `_guard` dropped here and the lock is released

try_lock_path()

let path = "path/to/my/file.txt";

match fmutex::try_lock_path(path)? {
    Some(_guard) => {

        // do mutually exclusive stuff here

    } // <-- `_guard` dropped here and the lock is released

    None => {
        eprintln!("the lock could not be acquired!");
    }
}

License

This project is distributed under the terms of both the MIT license and the Apache License (Version 2.0).

See LICENSE-APACHE and LICENSE-MIT for details.

Dependencies

~0–7.5MB
~52K SLoC