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 <windows.h> // CreateFileW
5 #include "cmFileLock.h"
6 #include "cmSystemTools.h"
8 cmFileLock::cmFileLock()
12 cmFileLockResult
cmFileLock::Release()
14 if (this->Filename
.empty()) {
15 return cmFileLockResult::MakeOk();
17 const unsigned long len
= static_cast<unsigned long>(-1);
18 static OVERLAPPED overlapped
;
19 const DWORD reserved
= 0;
20 const BOOL unlockResult
=
21 UnlockFileEx(File
, reserved
, len
, len
, &overlapped
);
25 CloseHandle(this->File
);
26 this->File
= INVALID_HANDLE_VALUE
;
29 return cmFileLockResult::MakeOk();
31 return cmFileLockResult::MakeSystem();
35 cmFileLockResult
cmFileLock::OpenFile()
37 const DWORD access
= GENERIC_READ
| GENERIC_WRITE
;
38 const DWORD shareMode
= FILE_SHARE_READ
| FILE_SHARE_WRITE
;
39 const PSECURITY_ATTRIBUTES security
= nullptr;
41 const HANDLE templ
= nullptr;
42 this->File
= CreateFileW(
43 cmSystemTools::ConvertToWindowsExtendedPath(this->Filename
).c_str(),
44 access
, shareMode
, security
, OPEN_EXISTING
, attr
, templ
);
45 if (this->File
== INVALID_HANDLE_VALUE
) {
46 return cmFileLockResult::MakeSystem();
48 return cmFileLockResult::MakeOk();
52 cmFileLockResult
cmFileLock::LockWithoutTimeout()
54 if (!this->LockFile(LOCKFILE_EXCLUSIVE_LOCK
)) {
55 return cmFileLockResult::MakeSystem();
57 return cmFileLockResult::MakeOk();
61 cmFileLockResult
cmFileLock::LockWithTimeout(unsigned long seconds
)
63 const DWORD flags
= LOCKFILE_EXCLUSIVE_LOCK
| LOCKFILE_FAIL_IMMEDIATELY
;
65 const BOOL result
= this->LockFile(flags
);
67 return cmFileLockResult::MakeOk();
69 const DWORD error
= GetLastError();
70 if (error
!= ERROR_LOCK_VIOLATION
) {
71 return cmFileLockResult::MakeSystem();
74 return cmFileLockResult::MakeTimeout();
77 cmSystemTools::Delay(1000);
81 int cmFileLock::LockFile(int flags
)
83 const DWORD reserved
= 0;
84 const unsigned long len
= static_cast<unsigned long>(-1);
85 static OVERLAPPED overlapped
;
86 return LockFileEx(this->File
, flags
, reserved
, len
, len
, &overlapped
);