proxmox/tools/fs: add shared lock helper

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
This commit is contained in:
Dominik Csapak 2020-09-25 16:13:14 +02:00 committed by Dietmar Maurer
parent b9552a97e9
commit 115f003742

View File

@ -505,15 +505,26 @@ pub fn lock_file<F: AsRawFd>(
Ok(())
}
/// Open or create a lock file (append mode). Then try to
/// acquire a shared lock using `lock_file()`.
pub fn open_file_locked_shared<P: AsRef<Path>>(path: P, timeout: Duration) -> Result<File, Error> {
open_file_locked_impl(path, timeout, false)
}
/// Open or create a lock file (append mode). Then try to
/// acquire a lock using `lock_file()`.
pub fn open_file_locked<P: AsRef<Path>>(path: P, timeout: Duration) -> Result<File, Error> {
open_file_locked_impl(path, timeout, true)
}
fn open_file_locked_impl<P: AsRef<Path>>(path: P, timeout: Duration, exclusive: bool) -> Result<File, Error> {
let path = path.as_ref();
let mut file = match OpenOptions::new().create(true).append(true).open(path) {
Ok(file) => file,
Err(err) => bail!("Unable to open lock {:?} - {}", path, err),
};
match lock_file(&mut file, true, Some(timeout)) {
match lock_file(&mut file, exclusive, Some(timeout)) {
Ok(_) => Ok(file),
Err(err) => bail!("Unable to acquire lock {:?} - {}", path, err),
}