我找不到任何类似于文件锁定的东西,比如Linux中的一些程序用来阻止多个实例运行.在Python中,我会使用pylockfile.

我是忽略了Rust中类似的功能,还是应该从头开始实现它?

我并不懒惰,只是尽可能少地 retrofit 车轮

推荐答案

对于当代 rust 病(1.8+),应使用fs2 crate.它是一个跨平台库,提供一些标准库中找不到的文件系统功能,包括文件锁定.

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(())
}

我们可以看到,这两个进程是按顺序排列的,等待文件锁定.

$ ./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

Rust相关问答推荐

移植带有可变borrow 的C代码-卸载期间错误(nappgui示例)

将已知大小的切片合并成一个数组,

为什么我的梅森素数代码的指数越大,速度就越快?

交叉术语未正确清除屏幕

Pin<;&;mut可能将Uninit<;T>;>;合并为Pin<;&;mut T>;

是否可以在不直接重复的情况下为许多特定类型实现一个函数?

如何将 struct 数组放置在另一个 struct 的末尾而不进行内存分段

.在 Rust 模块标识符中

Rust Axum 框架 - 解包安全吗?

Rust 1.70 中未找到 Trait 实现

Rust:为什么 Pin 必须持有指针?

相当于 Rust 中 C++ 的 std::istringstream

为什么 Rust 字符串没有短字符串优化 (SSO)?

Rust中如何实现一个与Sized相反的负特性(Unsized)

(let b = MyBox(5 as *const u8); &b; ) 和 (let b = &MyBox(5 as *const u8); ) 之间有什么区别

分配给下划线模式时会发生什么?

从嵌入式 Rust 中的某个时刻开始经过的时间

为什么指定生命周期让我返回一个引用?

使用 rust-sqlx/tokio 时如何取消长时间运行的查询

当引用不再被borrow 时,Rust 不会得到它