#lock-files #lock #file #file-path #mutex #raii #file-descriptor

fmutex

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

3 unstable releases

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

#155 in Filesystem

Download history 396/week @ 2024-11-18 109/week @ 2024-11-25 126/week @ 2024-12-02 86/week @ 2024-12-09 201/week @ 2024-12-16 308/week @ 2024-12-23 132/week @ 2024-12-30 371/week @ 2025-01-06 771/week @ 2025-01-13 415/week @ 2025-01-20 611/week @ 2025-01-27 689/week @ 2025-02-03 608/week @ 2025-02-10 845/week @ 2025-02-17 561/week @ 2025-02-24 772/week @ 2025-03-03

2,838 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
~53K SLoC