From 8cd29fb24a2d6784d31626f8f633cb3199e9aa44 Mon Sep 17 00:00:00 2001 From: Stefan Reiter Date: Wed, 29 Jul 2020 14:33:12 +0200 Subject: [PATCH] tools: add nonblocking mode to lock_file Signed-off-by: Stefan Reiter --- src/tools.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/tools.rs b/src/tools.rs index 44db796d..d7b72a73 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -91,6 +91,9 @@ pub fn map_struct_mut(buffer: &mut [u8]) -> Result<&mut T, Error> { /// Create a file lock using fntl. This function allows you to specify /// a timeout if you want to avoid infinite blocking. +/// +/// With timeout set to 0, non-blocking mode is used and the function +/// will fail immediately if the lock can't be acquired. pub fn lock_file( file: &mut F, exclusive: bool, @@ -110,6 +113,16 @@ pub fn lock_file( Some(t) => t, }; + if timeout.as_nanos() == 0 { + let lockarg = if exclusive { + nix::fcntl::FlockArg::LockExclusiveNonblock + } else { + nix::fcntl::FlockArg::LockSharedNonblock + }; + nix::fcntl::flock(file.as_raw_fd(), lockarg)?; + return Ok(()); + } + // unblock the timeout signal temporarily let _sigblock_guard = timer::unblock_timeout_signal();