#file-lock #locking #file #lock #fs-file #flock

file_locking

A lean file locking implementation for Unix and Windows

1 unstable release

0.1.0 Dec 15, 2024

#10 in #flock

Download history 129/week @ 2024-12-12 8/week @ 2024-12-19

137 downloads per month

MIT license

21KB
279 lines

Simple, Lightweight File Locking

This crate provides an extremely lean implementation of file locking for #[cfg(unix)] (using the libc crate) and #[cfg(windows)] (using the windows-sys crate) systems.

The API is exposed as a single extension trait for std::fs::File called FileExt. Simply bring the trait into scope, and you can lock files to your heart's content:

use std::fs::{ File };
use file_locking::{ FileExt };

let f = File::options()
  .create(true)
  .write(true)
  .open("database.lock")?;

{
  let _guard = f.lock_exclusive()?;

  // ... do some stuff with the knowledge that nobody else can lock the file ...
}

// the lock is now released and can be taken again by somebody else c:

Portability

Some unavoidable behavior differences exist between platforms. To summarize:

  • Don't count on file locks to prevent read or write access to a file, but be prepared for them to.
  • Don't lock the same on-disk file through the same File object more than once.

License

This project is made available under the terms of the MIT license. See LICENSE.md for details.

Contributing

Bug reports, feature requests, and patch submissions are welcome at contact@echowritescode.dev.

Dependencies

~0–8MB
~55K SLoC