file_lock.cpp 923 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include "file_lock.h"
  2. #include "flock.h"
  3. #include <util/generic/yexception.h>
  4. #include <cerrno>
  5. namespace {
  6. int GetMode(const EFileLockType type) {
  7. switch (type) {
  8. case EFileLockType::Exclusive:
  9. return LOCK_EX;
  10. case EFileLockType::Shared:
  11. return LOCK_SH;
  12. default:
  13. Y_UNREACHABLE();
  14. }
  15. Y_UNREACHABLE();
  16. }
  17. } // namespace
  18. TFileLock::TFileLock(const TString& filename, const EFileLockType type)
  19. : TFile(filename, OpenAlways | RdOnly)
  20. , Type(type)
  21. {
  22. }
  23. void TFileLock::Acquire() {
  24. Flock(GetMode(Type));
  25. }
  26. bool TFileLock::TryAcquire() {
  27. try {
  28. Flock(GetMode(Type) | LOCK_NB);
  29. return true;
  30. } catch (const TSystemError& e) {
  31. if (e.Status() != EWOULDBLOCK) {
  32. throw;
  33. }
  34. return false;
  35. }
  36. }
  37. void TFileLock::Release() {
  38. Flock(LOCK_UN);
  39. }