cmFileLockUnix.cxx 1.8 KB

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