Skip to main content

lock_file

Function lock_file 

Source
pub fn lock_file<'a, RF>(
    fd: &'a RF,
    flock: Option<flock>,
    locktype: Option<FcntlLockType>,
) -> Result<bool, FcntlError>
where RF: AsRawFd,
Expand description

Locks the given file (using FcntlCmd::SetLock). If flock is None all parameters of the flock structure ( l_whence, l_start, l_len, l_pid) will be set to 0. locktype controls the l_type parameter. When it is None, FcntlLockType::Read is used. flock.l_type will be overwritten in all cases to avoid passing an invalid parameter to the syscall.

The caller is responsible that fd was opened with the appropriate parameters, as stated by fcntl 2:

In order to place a read lock, fd must be open for reading. In order to place a write lock, fd must be open for writing. To place both types of lock, open a file read-write.

use std::fs::OpenOptions;
use fcntl::{FcntlLockType, lock_file};

let file = OpenOptions::new().read(true).write(true).open(file_name).unwrap();
match lock_file(&file, None, Some(FcntlLockType::Write)) {
    Ok(true) => println!("Lock acuired!"),
    Ok(false) => println!("Could not acquire lock!"),
    Err(err) => println!("Error: {:?}", err),
}