From 9bcbc8f919fc1c779d3b9c649dcbe3606fdbed32 Mon Sep 17 00:00:00 2001 From: Mike Buland Date: Fri, 25 May 2018 14:17:20 -0700 Subject: Added locking support to Bu::File. --- src/stable/file.cpp | 16 ++++++++++++++++ src/stable/file.h | 19 +++++++++++++++++++ 2 files changed, 35 insertions(+) (limited to 'src') diff --git a/src/stable/file.cpp b/src/stable/file.cpp index 35933f1..a15f394 100644 --- a/src/stable/file.cpp +++ b/src/stable/file.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -200,6 +201,21 @@ void Bu::File::setBlocking( bool bBlocking ) #endif } +bool Bu::File::canLock() const +{ + return true; +} + +void Bu::File::lock( bool bExclusive ) +{ + ::flock( fd, bExclusive?LOCK_EX:LOCK_SH ); +} + +void Bu::File::unlock() +{ + ::flock( fd, LOCK_UN ); +} + Bu::File Bu::File::tempFile( Bu::String &sName ) { int iXes; diff --git a/src/stable/file.h b/src/stable/file.h index e3497d3..6e05dc7 100644 --- a/src/stable/file.h +++ b/src/stable/file.h @@ -56,6 +56,25 @@ namespace Bu virtual bool isBlocking(); virtual void setBlocking( bool bBlocking=true ); + /** + * Tells you if advisory locks are supported. + */ + bool canLock() const; + + /** + * Acquires an advisory lock on the file. On posix/linux this is done + * via flock. + *@param bExclusive Set to true to acquire an exclusive lock (i.e. a + * write lock). If this is false then a shared lock (i.e. read lock) is + * acquired. A file cannot have both an exclusive and shared lock. + */ + void lock( bool bExclusive=true ); + + /** + * Release the held advisory lock. + */ + void unlock(); + enum { // Flags Read = 0x01, ///< Open file for reading -- cgit v1.2.3