cmFileLock.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. #include "cmConfigure.h" // IWYU pragma: keep
  5. #include <string>
  6. #if defined(_WIN32)
  7. # include <windows.h> // HANDLE
  8. #endif
  9. class cmFileLockResult;
  10. /**
  11. * @brief Cross-platform file locking.
  12. * @details Under the hood this class use 'fcntl' for Unix-like platforms and
  13. * 'LockFileEx'/'UnlockFileEx' for Win32 platform. Locks are exclusive and
  14. * advisory.
  15. */
  16. class cmFileLock
  17. {
  18. public:
  19. cmFileLock();
  20. ~cmFileLock();
  21. cmFileLock(cmFileLock const&) = delete;
  22. cmFileLock(cmFileLock&&) noexcept;
  23. cmFileLock& operator=(cmFileLock const&) = delete;
  24. cmFileLock& operator=(cmFileLock&&) noexcept;
  25. /**
  26. * @brief Lock the file.
  27. * @param timeoutSec Lock timeout. If -1 try until success or fatal error.
  28. */
  29. cmFileLockResult Lock(const std::string& filename, unsigned long timeoutSec);
  30. /**
  31. * @brief Unlock the file.
  32. */
  33. cmFileLockResult Release();
  34. /**
  35. * @brief Check file is locked by this class.
  36. * @details This function helps to find double locks (deadlocks) and to do
  37. * explicit unlocks.
  38. */
  39. bool IsLocked(const std::string& filename) const;
  40. private:
  41. cmFileLockResult OpenFile();
  42. cmFileLockResult LockWithoutTimeout();
  43. cmFileLockResult LockWithTimeout(unsigned long timeoutSec);
  44. #if defined(_WIN32)
  45. HANDLE File = INVALID_HANDLE_VALUE;
  46. BOOL LockFile(DWORD flags);
  47. #else
  48. int File = -1;
  49. int LockFile(int cmd, int type) const;
  50. #endif
  51. std::string Filename;
  52. };