2个不稳定版本
| 0.2.0 | 2024年3月9日 | 
|---|---|
| 0.1.0 | 2021年12月26日 | 
#79 in 操作系统
121,191 每月下载量
用于 533 个crate(2个直接使用)
24KB
308 行
file-guard
一个Rust中的跨平台简单建议性文件锁定库。
查看文档获取详细信息!
该锁支持对打开的File对象的字节范围进行独占和共享锁定模式。独占锁定文件的一部分将拒绝所有其他进程对文件指定区域的共享和独占访问。共享锁定文件的一部分将拒绝所有进程对文件指定区域的独占访问。锁定范围不需要存在于文件中,并且这些范围可以用于进程之间的任何任意建议性锁定协议。
lock()、try_lock()或lock_any()的结果是一个FileGuard。当它被丢弃时,这个FileGuard将解锁当前持有的文件区域。独占锁可以被.downgrade()转换为跨平台的共享锁。
在 Unix 系统中,使用 fcntl 来执行锁定,而在 Windows 上则使用 LockFileEx。所有通用行为在各个平台上一致。对于特定平台的行为,可以使用相应的特性。例如,在 Windows 上,锁不能安全升级,而在 Unix 系统上,可以安全且原子性地进行升级。要使用此功能,可以使用 file_guard::os::unix::FileGuardExt,并使用 use,启用 .upgrade() 和 .try_upgrade() 方法。
请注意,在 Windows 上,必须以写权限打开文件才能对其进行锁定。
示例
use file_guard::Lock;
use std::fs::OpenOptions;
let mut file = OpenOptions::new()
    .read(true)
    .write(true)
    .create(true)
    .open("example-lock")?;
let mut lock = file_guard::lock(&mut file, Lock::Exclusive, 0, 1)?;
write_to_file(&mut lock)?;
// the lock will be unlocked when it goes out of scope
您可以在结构体中存储一个或多个锁
use file_guard::{FileGuard, Lock};
use std::fs::{File, OpenOptions};
let file = OpenOptions::new()
    .read(true)
    .write(true)
    .create(true)
    .open("example-lock")?;
struct Thing<'file> {
    a: FileGuard<&'file File>,
    b: FileGuard<&'file File>,
}
let t = Thing {
    a: file_guard::lock(&file, Lock::Exclusive, 0, 1)?,
    b: file_guard::lock(&file, Lock::Shared, 1, 2)?,
};
// both locks will be unlocked when t goes out of scope
任何可以 Deref 或 DerefMut 到 File 的内容都可以与 FileGuard 一起使用。这适用于 Rc<File>
use file_guard::{FileGuard, Lock};
use std::fs::{File, OpenOptions};
use std::rc::Rc;
let file = Rc::new(
    OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .open("example-lock")?
);
struct Thing {
    a: FileGuard<Rc<File>>,
    b: FileGuard<Rc<File>>,
}
let t = Thing {
    a: file_guard::lock(file.clone(), Lock::Exclusive, 0, 1)?,
    b: file_guard::lock(file, Lock::Shared, 1, 2)?,
};
// both locks will be unlocked and the file will be closed when t goes out of scope
依赖项
~215KB