cmFileLockWin32.cxx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 <windows.h> // CreateFileW
  6. cmFileLock::cmFileLock()
  7. {
  8. }
  9. cmFileLockResult cmFileLock::Release()
  10. {
  11. if (this->Filename.empty()) {
  12. return cmFileLockResult::MakeOk();
  13. }
  14. const unsigned long len = static_cast<unsigned long>(-1);
  15. static OVERLAPPED overlapped;
  16. const DWORD reserved = 0;
  17. const BOOL unlockResult =
  18. UnlockFileEx(File, reserved, len, len, &overlapped);
  19. this->Filename = "";
  20. CloseHandle(this->File);
  21. this->File = INVALID_HANDLE_VALUE;
  22. if (unlockResult) {
  23. return cmFileLockResult::MakeOk();
  24. } else {
  25. return cmFileLockResult::MakeSystem();
  26. }
  27. }
  28. cmFileLockResult cmFileLock::OpenFile()
  29. {
  30. const DWORD access = GENERIC_READ | GENERIC_WRITE;
  31. const DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  32. const PSECURITY_ATTRIBUTES security = NULL;
  33. const DWORD attr = 0;
  34. const HANDLE templ = NULL;
  35. this->File = CreateFileW(
  36. cmSystemTools::ConvertToWindowsExtendedPath(this->Filename).c_str(),
  37. access, shareMode, security, OPEN_EXISTING, attr, templ);
  38. if (this->File == INVALID_HANDLE_VALUE) {
  39. return cmFileLockResult::MakeSystem();
  40. } else {
  41. return cmFileLockResult::MakeOk();
  42. }
  43. }
  44. cmFileLockResult cmFileLock::LockWithoutTimeout()
  45. {
  46. if (!this->LockFile(LOCKFILE_EXCLUSIVE_LOCK)) {
  47. return cmFileLockResult::MakeSystem();
  48. } else {
  49. return cmFileLockResult::MakeOk();
  50. }
  51. }
  52. cmFileLockResult cmFileLock::LockWithTimeout(unsigned long seconds)
  53. {
  54. const DWORD flags = LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY;
  55. while (true) {
  56. const BOOL result = this->LockFile(flags);
  57. if (result) {
  58. return cmFileLockResult::MakeOk();
  59. }
  60. const DWORD error = GetLastError();
  61. if (error != ERROR_LOCK_VIOLATION) {
  62. return cmFileLockResult::MakeSystem();
  63. }
  64. if (seconds == 0) {
  65. return cmFileLockResult::MakeTimeout();
  66. }
  67. --seconds;
  68. cmSystemTools::Delay(1000);
  69. }
  70. }
  71. BOOL cmFileLock::LockFile(DWORD flags)
  72. {
  73. const DWORD reserved = 0;
  74. const unsigned long len = static_cast<unsigned long>(-1);
  75. static OVERLAPPED overlapped;
  76. return LockFileEx(this->File, flags, reserved, len, len, &overlapped);
  77. }