cmFileLock.h 1.4 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. #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. CM_DISABLE_COPY(cmFileLock)
  20. public:
  21. cmFileLock();
  22. ~cmFileLock();
  23. /**
  24. * @brief Lock the file.
  25. * @param timeoutSec Lock timeout. If -1 try until success or fatal error.
  26. */
  27. cmFileLockResult Lock(const std::string& filename, unsigned long timeoutSec);
  28. /**
  29. * @brief Unlock the file.
  30. */
  31. cmFileLockResult Release();
  32. /**
  33. * @brief Check file is locked by this class.
  34. * @details This function helps to find double locks (deadlocks) and to do
  35. * explicit unlocks.
  36. */
  37. bool IsLocked(const std::string& filename) const;
  38. private:
  39. cmFileLockResult OpenFile();
  40. cmFileLockResult LockWithoutTimeout();
  41. cmFileLockResult LockWithTimeout(unsigned long timeoutSec);
  42. #if defined(_WIN32)
  43. HANDLE File = INVALID_HANDLE_VALUE;
  44. BOOL LockFile(DWORD flags);
  45. #else
  46. int File = -1;
  47. int LockFile(int cmd, int type);
  48. #endif
  49. std::string Filename;
  50. };
  51. #endif // cmFileLock_h