Rust中有文件锁定吗?

aya*_*ami 14 synchronization locking rust

我现在正在学习Rust大约3个小时,并且找不到任何类似于文件锁定的东西(你知道,就像Linux中的一些程序用来阻止多个实例运行).

例如在Python中,我将使用此模块:https://github.com/openstack/pylockfile

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

不是懒惰,只是试图重新发明尽可能少的车轮.

ken*_*ytm 14

对于当代Rust(1.8+),您应该使用fs2板条箱.它是一个跨平台的库,提供标准库中没有的一些文件系统功能,包括文件锁定.

fs2文件锁定函数flock(2)在UNIX和LockFileExWindows 上内部使用.

例:

//! 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(())
}
Run Code Online (Sandbox Code Playgroud)

我们可以看到两个进程按顺序等待文件锁定.

$ ./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
Run Code Online (Sandbox Code Playgroud)


Den*_*din 6

在 Linux 中,您可以使用nix crate包装unix 文件锁。

这是一个例子:

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!");
}
Run Code Online (Sandbox Code Playgroud)

如果您尝试运行两个实例,第二个实例将仅在第一个实例解锁文件后开始倒计时。但其他程序可以忽略这个锁:

chunk(2):函数仅放置咨询锁;给定文件的适当权限,进程可以自由地忽略flock()的使用并在文件上执行I/O。