1 //===--- LockFileManager.h - File-level locking utility ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_SUPPORT_LOCKFILEMANAGER_H
10 #define LLVM_SUPPORT_LOCKFILEMANAGER_H
12 #include "llvm/ADT/Optional.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/StringRef.h"
15 #include <system_error>
16 #include <utility> // for std::pair
19 /// \brief Class that manages the creation of a lock file to aid
20 /// implicit coordination between different processes.
22 /// The implicit coordination works by creating a ".lock" file alongside
23 /// the file that we're coordinating for, using the atomicity of the file
24 /// system to ensure that only a single process can create that ".lock" file.
25 /// When the lock file is removed, the owning process has finished the
27 class LockFileManager {
29 /// \brief Describes the state of a lock file.
31 /// \brief The lock file has been created and is owned by this instance
34 /// \brief The lock file already exists and is owned by some other
37 /// \brief An error occurred while trying to create or find the lock
42 /// \brief Describes the result of waiting for the owner to release the lock.
43 enum WaitForUnlockResult {
44 /// \brief The lock was released successfully.
46 /// \brief Owner died while holding the lock.
48 /// \brief Reached timeout while waiting for the owner to release the lock.
53 SmallString<128> FileName;
54 SmallString<128> LockFileName;
55 SmallString<128> UniqueLockFileName;
57 Optional<std::pair<std::string, int> > Owner;
58 Optional<std::error_code> Error;
60 LockFileManager(const LockFileManager &) LLVM_DELETED_FUNCTION;
61 LockFileManager &operator=(const LockFileManager &) LLVM_DELETED_FUNCTION;
63 static Optional<std::pair<std::string, int> >
64 readLockFile(StringRef LockFileName);
66 static bool processStillExecuting(StringRef Hostname, int PID);
70 LockFileManager(StringRef FileName);
73 /// \brief Determine the state of the lock file.
74 LockFileState getState() const;
76 operator LockFileState() const { return getState(); }
78 /// \brief For a shared lock, wait until the owner releases the lock.
79 WaitForUnlockResult waitForUnlock();
82 } // end namespace llvm
84 #endif // LLVM_SUPPORT_LOCKFILEMANAGER_H