From b5deadbeea24f46588376ae230a517e4a2d51766 Mon Sep 17 00:00:00 2001 From: oddcoder <ahmedsoliman@oddcoder.com> Date: Sun, 21 Jun 2020 12:30:11 +0200 Subject: [PATCH] Add (POSIX defined) struct flock struct flock is posix defined locking mechanism on *nix platform Example usage (copied from https://gavv.github.io/articles/file-locks/) : #include <fcntl.h> struct flock fl; memset(&fl, 0, sizeof(fl)); // lock in shared mode fl.l_type = F_RDLCK; // lock entire file fl.l_whence = SEEK_SET; // offset base is start of the file fl.l_start = 0; // starting offset is zero fl.l_len = 0; // len is zero, which is a special value representing end // of file (no matter how large the file grows in future) fl.l_pid = 0; // F_SETLK(W) ignores it; F_OFD_SETLK(W) requires it to be zero // F_SETLKW specifies blocking mode if (fcntl(fd, F_SETLKW, &fl) == -1) { exit(1); } // atomically upgrade shared lock to exclusive lock, but only // for bytes in range [10; 15) // // after this call, the process will hold three lock regions: // [0; 10) - shared lock // [10; 15) - exclusive lock // [15; SEEK_END) - shared lock fl.l_type = F_WRLCK; fl.l_start = 10; fl.l_len = 5; // F_SETLKW specifies non-blocking mode if (fcntl(fd, F_SETLK, &fl) == -1) { exit(1); } // release lock for bytes in range [10; 15) fl.l_type = F_UNLCK; if (fcntl(fd, F_SETLK, &fl) == -1) { exit(1); } // close file and release locks for all regions // remember that locks are released when process calls close() // on any descriptor for a lock file close(fd); --- src/header/fcntl/mod.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/header/fcntl/mod.rs b/src/header/fcntl/mod.rs index f7b20a56..1e9975c6 100644 --- a/src/header/fcntl/mod.rs +++ b/src/header/fcntl/mod.rs @@ -32,7 +32,14 @@ pub const F_UNLCK: c_int = 2; pub unsafe extern "C" fn creat(path: *const c_char, mode: mode_t) -> c_int { sys_open(path, O_WRONLY | O_CREAT | O_TRUNC, mode) } - +#[repr(C)] +pub struct flock { + pub l_type: c_short, + pub l_whence: c_short, + pub l_start: off_t, + pub l_len: off_t, + pub l_pid: pid_t, +} #[no_mangle] pub extern "C" fn sys_fcntl(fildes: c_int, cmd: c_int, arg: c_int) -> c_int { Sys::fcntl(fildes, cmd, arg) @@ -43,3 +50,6 @@ pub unsafe extern "C" fn sys_open(path: *const c_char, oflag: c_int, mode: mode_ let path = CStr::from_ptr(path); Sys::open(path, oflag, mode) } + +#[no_mangle] +pub unsafe extern "C" fn cbindgen_stupid_struct_user_for_fcntl(a: flock) {} -- GitLab