14

I'm learning Rust for about 3 hours now, and cannot find anything resembling file locking (you know, like some programs use in Linux to prevent multiple instances from running).

E.g. in Python, I'd use this module: https://github.com/openstack/pylockfile

Am I overlooking similar functionality in Rust, or should I just implement it from scratch?

Not lazy, just trying to reinvent as little wheels as possible.

  • 2
    There's come code to start from in rustdoc. It does say "This is not meant to be in the standard library". – Shepmaster Dec 14 '14 at 13:54
  • 2
    I think you may have to implement it from scratch. The IO/OS module is still very much in flux, and it is uncertain whether this functionality would or would not be a good fit for it... that being said, Rust has embraced packages distribution though Cargo from the start precisely for this reason, so create a small package dedicated to this functionality and share it with the world via crates.io – Matthieu M. Dec 14 '14 at 14:06
  • 1
    It's been a while since I had to think hard about file locking implementations, but that Python library seems like it is not thorough enough. It seems to mostly work by creating files / directories and seeing if they exist, not relying on the OS facilities. If you do reimplement file locking, I'd suggest checking out other resources to see how to do it. – Shepmaster Dec 14 '14 at 14:13
  • Thanks for your replies! I sure meant creating an external library, not adding things to std. – ayanami Dec 14 '14 at 14:51
  • 1
    BTW, if you want to create a daemon, then you would probably want to consider using your OS process management system, like systemd in Linux or launchd in OS X. That way you won't need to think about locks entirely. – Vladimir Matveev Dec 14 '14 at 22:15
11

For contemporary Rust (1.8+) you should use the fs2 crate. It is a cross-platform library that provides some file system functions not found in the standard library, including file locking.

fs2's file locking functions internally use flock(2) on UNIX and LockFileEx on Windows.

Example:

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

We can see that the two processes are sequenced waiting on the file lock.

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

In Linux you can use nix crate which wraps unix file lock.

Here is an example:

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!");
}

If you try to run two instances, the second will start to countdown only after first instance unlocked file. But another programs can ignore this lock:

flock(2): function places advisory locks only; given suitable permissions on a file, a process is free to ignore the use of flock() and perform I/O on the file.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.