summaryrefslogtreecommitdiffstats
path: root/util/system/file_lock.cpp
diff options
context:
space:
mode:
authorDevtools Arcadia <[email protected]>2022-02-07 18:08:42 +0300
committerDevtools Arcadia <[email protected]>2022-02-07 18:08:42 +0300
commit1110808a9d39d4b808aef724c861a2e1a38d2a69 (patch)
treee26c9fed0de5d9873cce7e00bc214573dc2195b7 /util/system/file_lock.cpp
intermediate changes
ref:cde9a383711a11544ce7e107a78147fb96cc4029
Diffstat (limited to 'util/system/file_lock.cpp')
-rw-r--r--util/system/file_lock.cpp46
1 files changed, 46 insertions, 0 deletions
diff --git a/util/system/file_lock.cpp b/util/system/file_lock.cpp
new file mode 100644
index 00000000000..45d91282c5b
--- /dev/null
+++ b/util/system/file_lock.cpp
@@ -0,0 +1,46 @@
+#include "file_lock.h"
+#include "flock.h"
+
+#include <util/generic/yexception.h>
+
+#include <cerrno>
+
+namespace {
+ int GetMode(const EFileLockType type) {
+ switch (type) {
+ case EFileLockType::Exclusive:
+ return LOCK_EX;
+ case EFileLockType::Shared:
+ return LOCK_SH;
+ default:
+ Y_UNREACHABLE();
+ }
+ Y_UNREACHABLE();
+ }
+}
+
+TFileLock::TFileLock(const TString& filename, const EFileLockType type)
+ : TFile(filename, OpenAlways | RdOnly)
+ , Type(type)
+{
+}
+
+void TFileLock::Acquire() {
+ Flock(GetMode(Type));
+}
+
+bool TFileLock::TryAcquire() {
+ try {
+ Flock(GetMode(Type) | LOCK_NB);
+ return true;
+ } catch (const TSystemError& e) {
+ if (e.Status() != EWOULDBLOCK) {
+ throw;
+ }
+ return false;
+ }
+}
+
+void TFileLock::Release() {
+ Flock(LOCK_UN);
+}