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