我找不到类似于文件锁定的东西,就像Linux中使用某些程序来阻止多个实例运行一样。在Python中,我将使用pylockfile。
我是在Rust中忽略了类似的功能,还是应该从头开始实现它?
我并不懒惰,只是在尝试尽可能减少车轮数量。
对于当代Rust(1.8+),应使用fs2
crate。它是一个跨平台的库,提供了一些标准库中找不到的文件系统功能,包括文件锁定。
fs2
的文件锁定功能flock(2)
在UNIX和LockFileEx
Windows上内部使用。
例子:
//! This program tries to lock a file, sleeps for N seconds, and then unlocks the file.
// cargo-deps: fs2
extern crate fs2;
use fs2::FileExt;
use std::io::Result;
use std::env::args;
use std::fs::File;
use std::time::Duration;
use std::thread::sleep;
fn main() {
run().unwrap();
}
fn run() -> Result<()> {
let sleep_seconds = args().nth(1).and_then(|arg| arg.parse().ok()).unwrap_or(0);
let sleep_duration = Duration::from_secs(sleep_seconds);
let file = File::open("file.lock")?;
println!("{}: Preparing to lock file.", sleep_seconds);
file.lock_exclusive()?; // block until this process can lock the file
println!("{}: Obtained lock.", sleep_seconds);
sleep(sleep_duration);
println!("{}: Sleep completed", sleep_seconds);
file.unlock()?;
println!("{}: Released lock, returning", sleep_seconds);
Ok(())
}
我们可以看到这两个进程是按顺序等待文件锁的。
$ ./a 4 & ./a 1
[1] 14894
4: Preparing to lock file.
4: Obtained lock.
1: Preparing to lock file.
4: Sleep completed
4: Released lock, returning
1: Obtained lock.
1: Sleep completed
1: Released lock, returning
[1]+ Done ./a 4
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句