cmFileLock.h 1.9 KB

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