我找不到类似于file锁的东西 就像某些程序在Linux中使用 防止多个实例运行。 在Python,我会使用pylockfile.。 我忽略了Rust的类似功能, 还是我应该从头开始实现它?
对于当代生锈(1.8+),您应该使用
。这是一个跨平台库,它提供了标准库中找不到的一些文件系统功能,包括文件锁定。
fs2
的文件锁定功能在UNIX上内部使用flock(2)
在Windows上使用。示例:
LockFileEx
我们可以看到这两个过程是在文件锁上等待的测序。
//! 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(())
}
在linux中,您可以使用
nix板条
这里是一个例子:
$ ./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
如果您尝试运行两个实例,则仅在第一个实例解锁文件后才开始倒计时。但是另一个程序可以忽略此锁:
:功能位置仅咨询锁;在文件上获得了适当的权限, 过程可以自由忽略羊群()的使用,而在文件上执行I/O。
也是crate作为跨平台解决方案。https://github.com/clucompany/cluflock
extern crate nix; use std::fs::File; use std::os::unix::io::AsRawFd; use nix::fcntl::{flock, FlockArg}; fn main() { let file = File::open("Cargo.toml").unwrap(); let fd = file.as_raw_fd(); flock(fd, FlockArg::LockExclusive).unwrap(); for rem in (1..20).rev() { println!("Remain: {} sec.", rem); std::thread::sleep(std::time::Duration::from_secs(1)); } drop(file); println!("File unlocked!"); }
似乎不再维护,另一种选择是