1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use std::fs::{File, OpenOptions};
use std::io;
use std::os::unix::prelude::*;
use std::path::Path;
#[derive(Debug)]
pub struct Lock {
_file: File,
}
impl Lock {
pub fn new(p: &Path, wait: bool, create: bool, exclusive: bool) -> io::Result<Lock> {
let file = OpenOptions::new()
.read(true)
.write(true)
.create(create)
.mode(libc::S_IRWXU as u32)
.open(p)?;
let mut operation = if exclusive { libc::LOCK_EX } else { libc::LOCK_SH };
if !wait {
operation |= libc::LOCK_NB
}
let ret = unsafe { libc::flock(file.as_raw_fd(), operation) };
if ret == -1 { Err(io::Error::last_os_error()) } else { Ok(Lock { _file: file }) }
}
pub fn error_unsupported(err: &io::Error) -> bool {
matches!(err.raw_os_error(), Some(libc::ENOTSUP) | Some(libc::ENOSYS))
}
}