1
0

cmFileLockUnix.cxx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 "cmSystemTools.h"
  15. cmFileLock::cmFileLock(): File(-1)
  16. {
  17. }
  18. cmFileLockResult cmFileLock::Release()
  19. {
  20. if (this->Filename.empty())
  21. {
  22. return cmFileLockResult::MakeOk();
  23. }
  24. const int lockResult = this->LockFile(F_SETLK, F_UNLCK);
  25. this->Filename = "";
  26. if (lockResult == 0)
  27. {
  28. return cmFileLockResult::MakeOk();
  29. }
  30. else
  31. {
  32. return cmFileLockResult::MakeSystem();
  33. }
  34. }
  35. cmFileLockResult cmFileLock::OpenFile()
  36. {
  37. this->File = ::open(this->Filename.c_str(), O_RDWR);
  38. if (this->File == -1)
  39. {
  40. return cmFileLockResult::MakeSystem();
  41. }
  42. else
  43. {
  44. return cmFileLockResult::MakeOk();
  45. }
  46. }
  47. cmFileLockResult cmFileLock::LockWithoutTimeout()
  48. {
  49. if (this->LockFile(F_SETLKW, F_WRLCK) == -1)
  50. {
  51. return cmFileLockResult::MakeSystem();
  52. }
  53. else
  54. {
  55. return cmFileLockResult::MakeOk();
  56. }
  57. }
  58. cmFileLockResult cmFileLock::LockWithTimeout(unsigned long seconds)
  59. {
  60. while (true)
  61. {
  62. if (this->LockFile(F_SETLK, F_WRLCK) == -1)
  63. {
  64. if (errno != EACCES && errno != EAGAIN)
  65. {
  66. return cmFileLockResult::MakeSystem();
  67. }
  68. }
  69. else
  70. {
  71. return cmFileLockResult::MakeOk();
  72. }
  73. if (seconds == 0)
  74. {
  75. return cmFileLockResult::MakeTimeout();
  76. }
  77. --seconds;
  78. cmSystemTools::Delay(1000);
  79. }
  80. }
  81. int cmFileLock::LockFile(int cmd, int type)
  82. {
  83. struct ::flock lock;
  84. lock.l_start = 0;
  85. lock.l_len = 0; // lock all bytes
  86. lock.l_pid = 0; // unused (for F_GETLK only)
  87. lock.l_type = static_cast<short>(type); // exclusive lock
  88. lock.l_whence = SEEK_SET;
  89. return ::fcntl(this->File, cmd, &lock);
  90. }