cmake/Source/cmFileLock.h

65 lines
1.5 KiB
C
Raw Normal View History

2016-10-30 18:24:19 +01:00
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
2021-09-14 00:13:48 +02:00
#pragma once
2015-04-27 22:25:09 +02:00
2018-01-26 17:06:56 +01:00
#include "cmConfigure.h" // IWYU pragma: keep
2016-10-30 18:24:19 +01:00
#include <string>
2015-04-27 22:25:09 +02:00
#if defined(_WIN32)
2018-08-09 18:06:22 +02:00
# include <windows.h> // HANDLE
2015-04-27 22:25:09 +02:00
#endif
class cmFileLockResult;
/**
2018-08-09 18:06:22 +02:00
* @brief Cross-platform file locking.
* @details Under the hood this class use 'fcntl' for Unix-like platforms and
* 'LockFileEx'/'UnlockFileEx' for Win32 platform. Locks are exclusive and
* advisory.
*/
2015-04-27 22:25:09 +02:00
class cmFileLock
{
2016-07-09 11:21:54 +02:00
public:
2015-04-27 22:25:09 +02:00
cmFileLock();
~cmFileLock();
2019-11-11 23:01:05 +01:00
cmFileLock(cmFileLock const&) = delete;
2020-08-30 11:54:41 +02:00
cmFileLock(cmFileLock&&) noexcept;
2019-11-11 23:01:05 +01:00
cmFileLock& operator=(cmFileLock const&) = delete;
2020-08-30 11:54:41 +02:00
cmFileLock& operator=(cmFileLock&&) noexcept;
2019-11-11 23:01:05 +01:00
2015-04-27 22:25:09 +02:00
/**
2018-08-09 18:06:22 +02:00
* @brief Lock the file.
* @param timeoutSec Lock timeout. If -1 try until success or fatal error.
*/
2015-04-27 22:25:09 +02:00
cmFileLockResult Lock(const std::string& filename, unsigned long timeoutSec);
/**
2018-08-09 18:06:22 +02:00
* @brief Unlock the file.
*/
2015-04-27 22:25:09 +02:00
cmFileLockResult Release();
/**
2018-08-09 18:06:22 +02:00
* @brief Check file is locked by this class.
* @details This function helps to find double locks (deadlocks) and to do
* explicit unlocks.
*/
2015-04-27 22:25:09 +02:00
bool IsLocked(const std::string& filename) const;
2016-07-09 11:21:54 +02:00
private:
2015-04-27 22:25:09 +02:00
cmFileLockResult OpenFile();
cmFileLockResult LockWithoutTimeout();
cmFileLockResult LockWithTimeout(unsigned long timeoutSec);
#if defined(_WIN32)
2019-11-11 23:01:05 +01:00
HANDLE File = INVALID_HANDLE_VALUE;
2015-04-27 22:25:09 +02:00
BOOL LockFile(DWORD flags);
#else
2019-11-11 23:01:05 +01:00
int File = -1;
2021-09-14 00:13:48 +02:00
int LockFile(int cmd, int type) const;
2015-04-27 22:25:09 +02:00
#endif
std::string Filename;
};