cmFileLockUnix.cxx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmFileLock.h"
  4. #include "cmSystemTools.h"
  5. #include <errno.h> // errno
  6. #include <fcntl.h>
  7. #include <stdio.h> // SEEK_SET
  8. #include <unistd.h>
  9. cmFileLock::cmFileLock() = default;
  10. cmFileLockResult cmFileLock::Release()
  11. {
  12. if (this->Filename.empty()) {
  13. return cmFileLockResult::MakeOk();
  14. }
  15. const int lockResult = this->LockFile(F_SETLK, F_UNLCK);
  16. this->Filename = "";
  17. ::close(this->File);
  18. this->File = -1;
  19. if (lockResult == 0) {
  20. return cmFileLockResult::MakeOk();
  21. }
  22. return cmFileLockResult::MakeSystem();
  23. }
  24. cmFileLockResult cmFileLock::OpenFile()
  25. {
  26. this->File = ::open(this->Filename.c_str(), O_RDWR);
  27. if (this->File == -1) {
  28. return cmFileLockResult::MakeSystem();
  29. }
  30. return cmFileLockResult::MakeOk();
  31. }
  32. cmFileLockResult cmFileLock::LockWithoutTimeout()
  33. {
  34. if (this->LockFile(F_SETLKW, F_WRLCK) == -1) {
  35. return cmFileLockResult::MakeSystem();
  36. }
  37. return cmFileLockResult::MakeOk();
  38. }
  39. cmFileLockResult cmFileLock::LockWithTimeout(unsigned long seconds)
  40. {
  41. while (true) {
  42. if (this->LockFile(F_SETLK, F_WRLCK) == -1) {
  43. if (errno != EACCES && errno != EAGAIN) {
  44. return cmFileLockResult::MakeSystem();
  45. }
  46. } else {
  47. return cmFileLockResult::MakeOk();
  48. }
  49. if (seconds == 0) {
  50. return cmFileLockResult::MakeTimeout();
  51. }
  52. --seconds;
  53. cmSystemTools::Delay(1000);
  54. }
  55. }
  56. int cmFileLock::LockFile(int cmd, int type)
  57. {
  58. struct ::flock lock;
  59. lock.l_start = 0;
  60. lock.l_len = 0; // lock all bytes
  61. lock.l_pid = 0; // unused (for F_GETLK only)
  62. lock.l_type = static_cast<short>(type); // exclusive lock
  63. lock.l_whence = SEEK_SET;
  64. return ::fcntl(this->File, cmd, &lock);
  65. }