Skip to content

Commit 95175f8

Browse files
authored
Rollup merge of #130999 - cberner:flock_pr, r=joboet
Implement file_lock feature This adds lock(), lock_shared(), try_lock(), try_lock_shared(), and unlock() to File gated behind the file_lock feature flag This is the initial implementation of #130994 for Unix and Windows platforms. I will follow it up with an implementation for WASI preview 2
2 parents d4abc31 + 9330786 commit 95175f8

File tree

10 files changed

+575
-0
lines changed

10 files changed

+575
-0
lines changed

library/std/src/fs.rs

+217
Original file line numberDiff line numberDiff line change
@@ -624,6 +624,223 @@ impl File {
624624
self.inner.datasync()
625625
}
626626

627+
/// Acquire an exclusive advisory lock on the file. Blocks until the lock can be acquired.
628+
///
629+
/// This acquires an exclusive advisory lock; no other file handle to this file may acquire
630+
/// another lock.
631+
///
632+
/// If this file handle, or a clone of it, already holds an advisory lock the exact behavior is
633+
/// unspecified and platform dependent, including the possibility that it will deadlock.
634+
/// However, if this method returns, then an exclusive lock is held.
635+
///
636+
/// If the file not open for writing, it is unspecified whether this function returns an error.
637+
///
638+
/// Note, this is an advisory lock meant to interact with [`lock_shared`], [`try_lock`],
639+
/// [`try_lock_shared`], and [`unlock`]. Its interactions with other methods, such as [`read`]
640+
/// and [`write`] are platform specific, and it may or may not cause non-lockholders to block.
641+
///
642+
/// # Platform-specific behavior
643+
///
644+
/// This function currently corresponds to the `flock` function on Unix with the `LOCK_EX` flag,
645+
/// and the `LockFileEx` function on Windows with the `LOCKFILE_EXCLUSIVE_LOCK` flag. Note that,
646+
/// this [may change in the future][changes].
647+
///
648+
/// [changes]: io#platform-specific-behavior
649+
///
650+
/// [`lock_shared`]: File::lock_shared
651+
/// [`try_lock`]: File::try_lock
652+
/// [`try_lock_shared`]: File::try_lock_shared
653+
/// [`unlock`]: File::unlock
654+
/// [`read`]: Read::read
655+
/// [`write`]: Write::write
656+
///
657+
/// # Examples
658+
///
659+
/// ```no_run
660+
/// #![feature(file_lock)]
661+
/// use std::fs::File;
662+
///
663+
/// fn main() -> std::io::Result<()> {
664+
/// let f = File::open("foo.txt")?;
665+
/// f.lock()?;
666+
/// Ok(())
667+
/// }
668+
/// ```
669+
#[unstable(feature = "file_lock", issue = "130994")]
670+
pub fn lock(&self) -> io::Result<()> {
671+
self.inner.lock()
672+
}
673+
674+
/// Acquire a shared advisory lock on the file. Blocks until the lock can be acquired.
675+
///
676+
/// This acquires a shared advisory lock; more than one file handle may hold a shared lock, but
677+
/// none may hold an exclusive lock.
678+
///
679+
/// If this file handle, or a clone of it, already holds an advisory lock, the exact behavior is
680+
/// unspecified and platform dependent, including the possibility that it will deadlock.
681+
/// However, if this method returns, then a shared lock is held.
682+
///
683+
/// Note, this is an advisory lock meant to interact with [`lock`], [`try_lock`],
684+
/// [`try_lock_shared`], and [`unlock`]. Its interactions with other methods, such as [`read`]
685+
/// and [`write`] are platform specific, and it may or may not cause non-lockholders to block.
686+
///
687+
/// # Platform-specific behavior
688+
///
689+
/// This function currently corresponds to the `flock` function on Unix with the `LOCK_SH` flag,
690+
/// and the `LockFileEx` function on Windows. Note that, this
691+
/// [may change in the future][changes].
692+
///
693+
/// [changes]: io#platform-specific-behavior
694+
///
695+
/// [`lock`]: File::lock
696+
/// [`try_lock`]: File::try_lock
697+
/// [`try_lock_shared`]: File::try_lock_shared
698+
/// [`unlock`]: File::unlock
699+
/// [`read`]: Read::read
700+
/// [`write`]: Write::write
701+
///
702+
/// # Examples
703+
///
704+
/// ```no_run
705+
/// #![feature(file_lock)]
706+
/// use std::fs::File;
707+
///
708+
/// fn main() -> std::io::Result<()> {
709+
/// let f = File::open("foo.txt")?;
710+
/// f.lock_shared()?;
711+
/// Ok(())
712+
/// }
713+
/// ```
714+
#[unstable(feature = "file_lock", issue = "130994")]
715+
pub fn lock_shared(&self) -> io::Result<()> {
716+
self.inner.lock_shared()
717+
}
718+
719+
/// Acquire an exclusive advisory lock on the file. Returns `Ok(false)` if the file is locked.
720+
///
721+
/// This acquires an exclusive advisory lock; no other file handle to this file may acquire
722+
/// another lock.
723+
///
724+
/// If this file handle, or a clone of it, already holds an advisory lock, the exact behavior is
725+
/// unspecified and platform dependent, including the possibility that it will deadlock.
726+
/// However, if this method returns, then an exclusive lock is held.
727+
///
728+
/// If the file not open for writing, it is unspecified whether this function returns an error.
729+
///
730+
/// Note, this is an advisory lock meant to interact with [`lock`], [`lock_shared`],
731+
/// [`try_lock_shared`], and [`unlock`]. Its interactions with other methods, such as [`read`]
732+
/// and [`write`] are platform specific, and it may or may not cause non-lockholders to block.
733+
///
734+
/// # Platform-specific behavior
735+
///
736+
/// This function currently corresponds to the `flock` function on Unix with the `LOCK_EX` and
737+
/// `LOCK_NB` flags, and the `LockFileEx` function on Windows with the `LOCKFILE_EXCLUSIVE_LOCK`
738+
/// and `LOCKFILE_FAIL_IMMEDIATELY` flags. Note that, this
739+
/// [may change in the future][changes].
740+
///
741+
/// [changes]: io#platform-specific-behavior
742+
///
743+
/// [`lock`]: File::lock
744+
/// [`lock_shared`]: File::lock_shared
745+
/// [`try_lock_shared`]: File::try_lock_shared
746+
/// [`unlock`]: File::unlock
747+
/// [`read`]: Read::read
748+
/// [`write`]: Write::write
749+
///
750+
/// # Examples
751+
///
752+
/// ```no_run
753+
/// #![feature(file_lock)]
754+
/// use std::fs::File;
755+
///
756+
/// fn main() -> std::io::Result<()> {
757+
/// let f = File::open("foo.txt")?;
758+
/// f.try_lock()?;
759+
/// Ok(())
760+
/// }
761+
/// ```
762+
#[unstable(feature = "file_lock", issue = "130994")]
763+
pub fn try_lock(&self) -> io::Result<bool> {
764+
self.inner.try_lock()
765+
}
766+
767+
/// Acquire a shared advisory lock on the file.
768+
/// Returns `Ok(false)` if the file is exclusively locked.
769+
///
770+
/// This acquires a shared advisory lock; more than one file handle may hold a shared lock, but
771+
/// none may hold an exclusive lock.
772+
///
773+
/// If this file handle, or a clone of it, already holds an advisory lock, the exact behavior is
774+
/// unspecified and platform dependent, including the possibility that it will deadlock.
775+
/// However, if this method returns, then a shared lock is held.
776+
///
777+
/// Note, this is an advisory lock meant to interact with [`lock`], [`try_lock`],
778+
/// [`try_lock`], and [`unlock`]. Its interactions with other methods, such as [`read`]
779+
/// and [`write`] are platform specific, and it may or may not cause non-lockholders to block.
780+
///
781+
/// # Platform-specific behavior
782+
///
783+
/// This function currently corresponds to the `flock` function on Unix with the `LOCK_SH` and
784+
/// `LOCK_NB` flags, and the `LockFileEx` function on Windows with the
785+
/// `LOCKFILE_FAIL_IMMEDIATELY` flag. Note that, this
786+
/// [may change in the future][changes].
787+
///
788+
/// [changes]: io#platform-specific-behavior
789+
///
790+
/// [`lock`]: File::lock
791+
/// [`lock_shared`]: File::lock_shared
792+
/// [`try_lock`]: File::try_lock
793+
/// [`unlock`]: File::unlock
794+
/// [`read`]: Read::read
795+
/// [`write`]: Write::write
796+
///
797+
/// # Examples
798+
///
799+
/// ```no_run
800+
/// #![feature(file_lock)]
801+
/// use std::fs::File;
802+
///
803+
/// fn main() -> std::io::Result<()> {
804+
/// let f = File::open("foo.txt")?;
805+
/// f.try_lock_shared()?;
806+
/// Ok(())
807+
/// }
808+
/// ```
809+
#[unstable(feature = "file_lock", issue = "130994")]
810+
pub fn try_lock_shared(&self) -> io::Result<bool> {
811+
self.inner.try_lock_shared()
812+
}
813+
814+
/// Release all locks on the file.
815+
///
816+
/// All remaining locks are released when the file handle, and all clones of it, are dropped.
817+
///
818+
/// # Platform-specific behavior
819+
///
820+
/// This function currently corresponds to the `flock` function on Unix with the `LOCK_UN` flag,
821+
/// and the `UnlockFile` function on Windows. Note that, this
822+
/// [may change in the future][changes].
823+
///
824+
/// [changes]: io#platform-specific-behavior
825+
///
826+
/// # Examples
827+
///
828+
/// ```no_run
829+
/// #![feature(file_lock)]
830+
/// use std::fs::File;
831+
///
832+
/// fn main() -> std::io::Result<()> {
833+
/// let f = File::open("foo.txt")?;
834+
/// f.lock()?;
835+
/// f.unlock()?;
836+
/// Ok(())
837+
/// }
838+
/// ```
839+
#[unstable(feature = "file_lock", issue = "130994")]
840+
pub fn unlock(&self) -> io::Result<()> {
841+
self.inner.unlock()
842+
}
843+
627844
/// Truncates or extends the underlying file, updating the size of
628845
/// this file to become `size`.
629846
///

library/std/src/fs/tests.rs

+118
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,124 @@ fn file_test_io_seek_and_write() {
203203
assert!(read_str == final_msg);
204204
}
205205

206+
#[test]
207+
fn file_lock_multiple_shared() {
208+
let tmpdir = tmpdir();
209+
let filename = &tmpdir.join("file_lock_multiple_shared_test.txt");
210+
let f1 = check!(File::create(filename));
211+
let f2 = check!(OpenOptions::new().write(true).open(filename));
212+
213+
// Check that we can acquire concurrent shared locks
214+
check!(f1.lock_shared());
215+
check!(f2.lock_shared());
216+
check!(f1.unlock());
217+
check!(f2.unlock());
218+
assert!(check!(f1.try_lock_shared()));
219+
assert!(check!(f2.try_lock_shared()));
220+
}
221+
222+
#[test]
223+
fn file_lock_blocking() {
224+
let tmpdir = tmpdir();
225+
let filename = &tmpdir.join("file_lock_blocking_test.txt");
226+
let f1 = check!(File::create(filename));
227+
let f2 = check!(OpenOptions::new().write(true).open(filename));
228+
229+
// Check that shared locks block exclusive locks
230+
check!(f1.lock_shared());
231+
assert!(!check!(f2.try_lock()));
232+
check!(f1.unlock());
233+
234+
// Check that exclusive locks block shared locks
235+
check!(f1.lock());
236+
assert!(!check!(f2.try_lock_shared()));
237+
}
238+
239+
#[test]
240+
fn file_lock_drop() {
241+
let tmpdir = tmpdir();
242+
let filename = &tmpdir.join("file_lock_dup_test.txt");
243+
let f1 = check!(File::create(filename));
244+
let f2 = check!(OpenOptions::new().write(true).open(filename));
245+
246+
// Check that locks are released when the File is dropped
247+
check!(f1.lock_shared());
248+
assert!(!check!(f2.try_lock()));
249+
drop(f1);
250+
assert!(check!(f2.try_lock()));
251+
}
252+
253+
#[test]
254+
fn file_lock_dup() {
255+
let tmpdir = tmpdir();
256+
let filename = &tmpdir.join("file_lock_dup_test.txt");
257+
let f1 = check!(File::create(filename));
258+
let f2 = check!(OpenOptions::new().write(true).open(filename));
259+
260+
// Check that locks are not dropped if the File has been cloned
261+
check!(f1.lock_shared());
262+
assert!(!check!(f2.try_lock()));
263+
let cloned = check!(f1.try_clone());
264+
drop(f1);
265+
assert!(!check!(f2.try_lock()));
266+
drop(cloned)
267+
}
268+
269+
#[test]
270+
#[cfg(windows)]
271+
fn file_lock_double_unlock() {
272+
let tmpdir = tmpdir();
273+
let filename = &tmpdir.join("file_lock_double_unlock_test.txt");
274+
let f1 = check!(File::create(filename));
275+
let f2 = check!(OpenOptions::new().write(true).open(filename));
276+
277+
// On Windows a file handle may acquire both a shared and exclusive lock.
278+
// Check that both are released by unlock()
279+
check!(f1.lock());
280+
check!(f1.lock_shared());
281+
assert!(!check!(f2.try_lock()));
282+
check!(f1.unlock());
283+
assert!(check!(f2.try_lock()));
284+
}
285+
286+
#[test]
287+
#[cfg(windows)]
288+
fn file_lock_blocking_async() {
289+
use crate::thread::{sleep, spawn};
290+
const FILE_FLAG_OVERLAPPED: u32 = 0x40000000;
291+
292+
let tmpdir = tmpdir();
293+
let filename = &tmpdir.join("file_lock_blocking_async.txt");
294+
let f1 = check!(File::create(filename));
295+
let f2 =
296+
check!(OpenOptions::new().custom_flags(FILE_FLAG_OVERLAPPED).write(true).open(filename));
297+
298+
check!(f1.lock());
299+
300+
// Ensure that lock() is synchronous when the file is opened for asynchronous IO
301+
let t = spawn(move || {
302+
check!(f2.lock());
303+
});
304+
sleep(Duration::from_secs(1));
305+
assert!(!t.is_finished());
306+
check!(f1.unlock());
307+
t.join().unwrap();
308+
309+
// Ensure that lock_shared() is synchronous when the file is opened for asynchronous IO
310+
let f2 =
311+
check!(OpenOptions::new().custom_flags(FILE_FLAG_OVERLAPPED).write(true).open(filename));
312+
check!(f1.lock());
313+
314+
// Ensure that lock() is synchronous when the file is opened for asynchronous IO
315+
let t = spawn(move || {
316+
check!(f2.lock_shared());
317+
});
318+
sleep(Duration::from_secs(1));
319+
assert!(!t.is_finished());
320+
check!(f1.unlock());
321+
t.join().unwrap();
322+
}
323+
206324
#[test]
207325
fn file_test_io_seek_shakedown() {
208326
// 01234567890123

library/std/src/sys/pal/hermit/fs.rs

+20
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,26 @@ impl File {
364364
self.fsync()
365365
}
366366

367+
pub fn lock(&self) -> io::Result<()> {
368+
unsupported()
369+
}
370+
371+
pub fn lock_shared(&self) -> io::Result<()> {
372+
unsupported()
373+
}
374+
375+
pub fn try_lock(&self) -> io::Result<bool> {
376+
unsupported()
377+
}
378+
379+
pub fn try_lock_shared(&self) -> io::Result<bool> {
380+
unsupported()
381+
}
382+
383+
pub fn unlock(&self) -> io::Result<()> {
384+
unsupported()
385+
}
386+
367387
pub fn truncate(&self, _size: u64) -> io::Result<()> {
368388
Err(Error::from_raw_os_error(22))
369389
}

0 commit comments

Comments
 (0)