cmFileLockUnix.cxx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*============================================================================
  2. CMake - Cross Platform Makefile Generator
  3. Copyright 2014 Ruslan Baratov
  4. Distributed under the OSI-approved BSD License (the "License");
  5. see accompanying file Copyright.txt for details.
  6. This software is distributed WITHOUT ANY WARRANTY; without even the
  7. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  8. See the License for more information.
  9. ============================================================================*/
  10. #include "cmFileLock.h"
  11. #include <errno.h> // errno
  12. #include <stdio.h> // SEEK_SET
  13. #include <fcntl.h>
  14. #include <unistd.h>
  15. #include "cmSystemTools.h"
  16. cmFileLock::cmFileLock(): File(-1)
  17. {
  18. }
  19. cmFileLockResult cmFileLock::Release()
  20. {
  21. if (this->Filename.empty())
  22. {
  23. return cmFileLockResult::MakeOk();
  24. }
  25. const int lockResult = this->LockFile(F_SETLK, F_UNLCK);
  26. this->Filename = "";
  27. ::close(this->File);
  28. this->File = -1;
  29. if (lockResult == 0)
  30. {
  31. return cmFileLockResult::MakeOk();
  32. }
  33. else
  34. {
  35. return cmFileLockResult::MakeSystem();
  36. }
  37. }
  38. cmFileLockResult cmFileLock::OpenFile()
  39. {
  40. this->File = ::open(this->Filename.c_str(), O_RDWR);
  41. if (this->File == -1)
  42. {
  43. return cmFileLockResult::MakeSystem();
  44. }
  45. else
  46. {
  47. return cmFileLockResult::MakeOk();
  48. }
  49. }
  50. cmFileLockResult cmFileLock::LockWithoutTimeout()
  51. {
  52. if (this->LockFile(F_SETLKW, F_WRLCK) == -1)
  53. {
  54. return cmFileLockResult::MakeSystem();
  55. }
  56. else
  57. {
  58. return cmFileLockResult::MakeOk();
  59. }
  60. }
  61. cmFileLockResult cmFileLock::LockWithTimeout(unsigned long seconds)
  62. {
  63. while (true)
  64. {
  65. if (this->LockFile(F_SETLK, F_WRLCK) == -1)
  66. {
  67. if (errno != EACCES && errno != EAGAIN)
  68. {
  69. return cmFileLockResult::MakeSystem();
  70. }
  71. }
  72. else
  73. {
  74. return cmFileLockResult::MakeOk();
  75. }
  76. if (seconds == 0)
  77. {
  78. return cmFileLockResult::MakeTimeout();
  79. }
  80. --seconds;
  81. cmSystemTools::Delay(1000);
  82. }
  83. }
  84. int cmFileLock::LockFile(int cmd, int type)
  85. {
  86. struct ::flock lock;
  87. lock.l_start = 0;
  88. lock.l_len = 0; // lock all bytes
  89. lock.l_pid = 0; // unused (for F_GETLK only)
  90. lock.l_type = static_cast<short>(type); // exclusive lock
  91. lock.l_whence = SEEK_SET;
  92. return ::fcntl(this->File, cmd, &lock);
  93. }