cmFileLockUnix.cxx 1.8 KB

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