cmFileLock.h 1.6 KB

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