Acquires an exclusive `flock(2)` on the given lock file path. Opens (or creates) the lock file and calls `flock(LOCK_EX)` in a blocking context. Returns the open `File` whose lifetime controls the lock duration -- dropping the file closes the fd and releases the lock.
(lock_path: PathBuf)
| 108 | /// context. Returns the open `File` whose lifetime controls the lock duration -- |
| 109 | /// dropping the file closes the fd and releases the lock. |
| 110 | async fn acquire_flock(lock_path: PathBuf) -> std::io::Result<File> { |
| 111 | tokio::task::spawn_blocking(move || { |
| 112 | let file = OpenOptions::new() |
| 113 | .read(true) |
| 114 | .write(true) |
| 115 | .create(true) |
| 116 | .truncate(false) |
| 117 | .open(&lock_path)?; |
| 118 | |
| 119 | // SAFETY: `file.as_raw_fd()` returns a valid fd from the open File above. |
| 120 | // `libc::flock` is a well-defined POSIX syscall that takes a valid fd. |
| 121 | let ret = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) }; |
| 122 | if ret != 0 { |
| 123 | return Err(std::io::Error::last_os_error()); |
| 124 | } |
| 125 | |
| 126 | Ok(file) |
| 127 | }) |
| 128 | .await |
| 129 | .expect("flock spawn_blocking task panicked") |
| 130 | } |
| 131 | |
| 132 | /// Represents an active proxy session for a single task. |
| 133 | /// |