Crate file_lock

source ·
Expand description

File locking via POSIX advisory record locks.

This crate provides the facility to obtain a write-lock and unlock a file following the advisory record lock scheme as specified by UNIX IEEE Std 1003.1-2001 (POSIX.1) via fcntl().

§Examples

Please note that the examples use tempfile merely to quickly create a file which is removed automatically. In the common case, you would want to lock a file which is known to multiple processes.

extern crate file_lock;

use file_lock::{FileLock, FileOptions};
use std::fs::OpenOptions;
use std::io::prelude::*;

fn main() {
    let should_we_block  = true;
    let options = FileOptions::new()
                        .write(true)
                        .create(true)
                        .append(true);

    let mut filelock = match FileLock::lock("myfile.txt", should_we_block, options) {
        Ok(lock) => lock,
        Err(err) => panic!("Error getting write lock: {}", err),
    };

    filelock.file.write_all(b"Hello, World!").is_ok();

    // Manually unlocking is optional as we unlock on Drop
    filelock.unlock();
}

Structs§

  • Represents the actually locked file
  • A wrapper around the open options type that can be queried for the write permissions