cmFileLockWin32.cxx 2.3 KB

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