cmFileLock.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. typedef HANDLE FileId;
  44. BOOL LockFile(DWORD flags);
  45. #else
  46. typedef int FileId;
  47. int LockFile(int cmd, int type);
  48. #endif
  49. FileId File;
  50. std::string Filename;
  51. };
  52. #endif // cmFileLock_h