cmFileLockUnix.cxx 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 "cmSystemTools.h"
  12. #include <errno.h> // errno
  13. #include <fcntl.h>
  14. #include <stdio.h> // SEEK_SET
  15. #include <unistd.h>
  16. cmFileLock::cmFileLock()
  17. : File(-1)
  18. {
  19. }
  20. cmFileLockResult cmFileLock::Release()
  21. {
  22. if (this->Filename.empty()) {
  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. return cmFileLockResult::MakeOk();
  31. }
  32. return cmFileLockResult::MakeSystem();
  33. }
  34. cmFileLockResult cmFileLock::OpenFile()
  35. {
  36. this->File = ::open(this->Filename.c_str(), O_RDWR);
  37. if (this->File == -1) {
  38. return cmFileLockResult::MakeSystem();
  39. }
  40. return cmFileLockResult::MakeOk();
  41. }
  42. cmFileLockResult cmFileLock::LockWithoutTimeout()
  43. {
  44. if (this->LockFile(F_SETLKW, F_WRLCK) == -1) {
  45. return cmFileLockResult::MakeSystem();
  46. }
  47. return cmFileLockResult::MakeOk();
  48. }
  49. cmFileLockResult cmFileLock::LockWithTimeout(unsigned long seconds)
  50. {
  51. while (true) {
  52. if (this->LockFile(F_SETLK, F_WRLCK) == -1) {
  53. if (errno != EACCES && errno != EAGAIN) {
  54. return cmFileLockResult::MakeSystem();
  55. }
  56. } else {
  57. return cmFileLockResult::MakeOk();
  58. }
  59. if (seconds == 0) {
  60. return cmFileLockResult::MakeTimeout();
  61. }
  62. --seconds;
  63. cmSystemTools::Delay(1000);
  64. }
  65. }
  66. int cmFileLock::LockFile(int cmd, int type)
  67. {
  68. struct ::flock lock;
  69. lock.l_start = 0;
  70. lock.l_len = 0; // lock all bytes
  71. lock.l_pid = 0; // unused (for F_GETLK only)
  72. lock.l_type = static_cast<short>(type); // exclusive lock
  73. lock.l_whence = SEEK_SET;
  74. return ::fcntl(this->File, cmd, &lock);
  75. }