Skip to content

Commit 7f73ce3

Browse files
author
Andy Grover
committed
Add flock(2) support
1 parent 23dc9e0 commit 7f73ce3

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ eventfd = []
1919
execvpe = []
2020

2121
[dependencies]
22-
libc = "0.1.8"
22+
libc = "0.1.10"
2323
bitflags = "0.1.1"
2424

2525
[dev-dependencies]

src/fcntl.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ pub use self::ffi::flock;
1111
mod ffi {
1212
pub use libc::{open, fcntl};
1313
pub use self::os::*;
14+
pub use libc::funcs::bsd44::flock as libc_flock;
15+
pub use libc::consts::os::bsd44::{LOCK_SH, LOCK_EX, LOCK_NB, LOCK_UN};
1416

1517
#[cfg(any(target_os = "linux", target_os = "android"))]
1618
mod os {
@@ -128,6 +130,36 @@ pub fn fcntl(fd: RawFd, arg: FcntlArg) -> Result<c_int> {
128130
Ok(res)
129131
}
130132

133+
pub enum FlockArg {
134+
LockShared,
135+
LockExclusive,
136+
Unlock,
137+
LockSharedNonblock,
138+
LockExclusiveNonblock,
139+
UnlockNonblock,
140+
}
141+
142+
pub fn flock(fd: RawFd, arg: FlockArg) -> Result<()> {
143+
use self::FlockArg::*;
144+
145+
let res = unsafe {
146+
match arg {
147+
LockShared => ffi::libc_flock(fd, ffi::LOCK_SH),
148+
LockExclusive => ffi::libc_flock(fd, ffi::LOCK_EX),
149+
Unlock => ffi::libc_flock(fd, ffi::LOCK_UN),
150+
LockSharedNonblock => ffi::libc_flock(fd, ffi::LOCK_SH | ffi::LOCK_NB),
151+
LockExclusiveNonblock => ffi::libc_flock(fd, ffi::LOCK_EX | ffi::LOCK_NB),
152+
UnlockNonblock => ffi::libc_flock(fd, ffi::LOCK_UN | ffi::LOCK_NB),
153+
}
154+
};
155+
156+
if res < 0 {
157+
return Err(Error::Sys(Errno::last()));
158+
}
159+
160+
Ok(())
161+
}
162+
131163
#[cfg(any(target_os = "linux", target_os = "android"))]
132164
mod consts {
133165
use libc::c_int;

0 commit comments

Comments
 (0)