]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_data_structures/src/flock/linux.rs
New upstream version 1.62.1+dfsg1
[rustc.git] / compiler / rustc_data_structures / src / flock / linux.rs
1 //! We use `flock` rather than `fcntl` on Linux, because WSL1 does not support
2 //! `fcntl`-style advisory locks properly (rust-lang/rust#72157). For other Unix
3 //! targets we still use `fcntl` because it's more portable than `flock`.
4
5 use std::fs::{File, OpenOptions};
6 use std::io;
7 use std::os::unix::prelude::*;
8 use std::path::Path;
9
10 #[derive(Debug)]
11 pub struct Lock {
12 _file: File,
13 }
14
15 impl Lock {
16 pub fn new(p: &Path, wait: bool, create: bool, exclusive: bool) -> io::Result<Lock> {
17 let file = OpenOptions::new()
18 .read(true)
19 .write(true)
20 .create(create)
21 .mode(libc::S_IRWXU as u32)
22 .open(p)?;
23
24 let mut operation = if exclusive { libc::LOCK_EX } else { libc::LOCK_SH };
25 if !wait {
26 operation |= libc::LOCK_NB
27 }
28
29 let ret = unsafe { libc::flock(file.as_raw_fd(), operation) };
30 if ret == -1 { Err(io::Error::last_os_error()) } else { Ok(Lock { _file: file }) }
31 }
32
33 pub fn error_unsupported(err: &io::Error) -> bool {
34 matches!(err.raw_os_error(), Some(libc::ENOTSUP) | Some(libc::ENOSYS))
35 }
36 }
37
38 // Note that we don't need a Drop impl to execute `flock(fd, LOCK_UN)`. A lock acquired by
39 // `flock` is associated with the file descriptor and closing the file releases it
40 // automatically.