Advisory cross-platform file locks using file descriptors, with async support by off-loading blocking operations to newly spawned blocking tasks. Adapted from yoshuawuyts/fd-lock, which was adapted from mafintosh/fd-lock.
Note that advisory lock compliance is opt-in, and can freely be ignored by other parties. This means this crate should never be used for security purposes, but solely to coordinate file access.
Basic usage
use std::path::PathBuf; use tokio::fs::File; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use async_fd_lock::{LockRead, LockWrite}; let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("foo.txt"); // Lock it for writing. { let mut write_guard = File::create_new(&path).await?.lock_write().await?; write_guard.write(b"bongo cat").await?; } // Lock it for reading. { let mut read_guard_1 = File::open(&path).await?.lock_read().await?; let mut read_guard_2 = File::open(&path).await?.lock_read().await?; let byte_1 = read_guard_1.read_u8().await?; let byte_2 = read_guard_2.read_u8().await?; }$ cargo add async-fd-lockThis crate uses unsafe on Windows to interface with windows-sys. All invariants have been carefully checked, and are manually enforced.
- LockFile function - WDC
- flock(2) - Linux Man Page
rustix::fs::flockwindows_sys::Win32::Storage::FileSystem::LockFile
MIT OR Apache-2.0