resolve cyclic dependency with zstd
[platform/upstream/cmake.git] / Source / cmFileLock.h
1 /* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
2    file Copyright.txt or https://cmake.org/licensing for details.  */
3 #pragma once
4
5 #include "cmConfigure.h" // IWYU pragma: keep
6
7 #include <string>
8
9 #if defined(_WIN32)
10 #  include <windows.h> // HANDLE
11 #endif
12
13 class cmFileLockResult;
14
15 /**
16  * @brief Cross-platform file locking.
17  * @details Under the hood this class use 'fcntl' for Unix-like platforms and
18  * 'LockFileEx'/'UnlockFileEx' for Win32 platform. Locks are exclusive and
19  * advisory.
20  */
21 class cmFileLock
22 {
23 public:
24   cmFileLock();
25   ~cmFileLock();
26
27   cmFileLock(cmFileLock const&) = delete;
28   cmFileLock(cmFileLock&&) noexcept;
29   cmFileLock& operator=(cmFileLock const&) = delete;
30   cmFileLock& operator=(cmFileLock&&) noexcept;
31
32   /**
33    * @brief Lock the file.
34    * @param timeoutSec Lock timeout. If -1 try until success or fatal error.
35    */
36   cmFileLockResult Lock(const std::string& filename, unsigned long timeoutSec);
37
38   /**
39    * @brief Unlock the file.
40    */
41   cmFileLockResult Release();
42
43   /**
44    * @brief Check file is locked by this class.
45    * @details This function helps to find double locks (deadlocks) and to do
46    * explicit unlocks.
47    */
48   bool IsLocked(const std::string& filename) const;
49
50 private:
51   cmFileLockResult OpenFile();
52   cmFileLockResult LockWithoutTimeout();
53   cmFileLockResult LockWithTimeout(unsigned long timeoutSec);
54
55 #if defined(_WIN32)
56   HANDLE File = INVALID_HANDLE_VALUE;
57   BOOL LockFile(DWORD flags);
58 #else
59   int File = -1;
60   int LockFile(int cmd, int type) const;
61 #endif
62
63   std::string Filename;
64 };