Version: SMASH-3.4
filelock.h
Go to the documentation of this file.
1 /*
2  *
3  * Copyright (c) 2015,2017-2018,2020,2022
4  * SMASH Team
5  *
6  * GNU General Public License (GPLv3 or later)
7  *
8  */
9 
10 #ifndef SRC_INCLUDE_SMASH_FILELOCK_H_
11 #define SRC_INCLUDE_SMASH_FILELOCK_H_
12 
13 #include <filesystem>
14 
15 #include "forwarddeclarations.h"
16 
17 namespace smash {
18 
19 /** Guard to create a file lock.
20  *
21  * This can be used to make sure concurrent processes do not interfere when for
22  * example writing files.
23  *
24  * The lock file will be deleted when the FileLock is destroyed.
25  *
26  * Internally this uses some POSIX system calls to atomically check for the
27  * existence of a file and create it if it does not exists. This works even
28  * over NFS (for at least NFSv3 and Linux 2.6).
29  */
30 class FileLock {
31  public:
32  /** Construct a file lock guard with a lock file at the given path.
33  *
34  * This will not create a file, use acquire() for that.
35  *
36  * \param[in] path Path to file.
37  * \return Constructed object.
38  */
39  explicit FileLock(const std::filesystem::path& path);
40  /// Delete the lock file when the guard is destroyed.
41  ~FileLock();
42  /** Try to acquire the file lock.
43  *
44  * \return Returns false if the file already exists.
45  * Returns true and creates the file otherwise.
46  *
47  * \throws std::runtime_error if called another time after returning
48  * true or if the lockfile cannot be closed.
49  */
50  bool acquire();
51 
52  private:
53  /// Path to the file lock.
54  std::filesystem::path path_;
55  /// Whether the lock has been acquired.
56  bool acquired_;
57 };
58 
59 } // namespace smash
60 
61 #endif // SRC_INCLUDE_SMASH_FILELOCK_H_
Guard to create a file lock.
Definition: filelock.h:30
bool acquired_
Whether the lock has been acquired.
Definition: filelock.h:56
bool acquire()
Try to acquire the file lock.
Definition: filelock.cc:22
~FileLock()
Delete the lock file when the guard is destroyed.
Definition: filelock.cc:41
FileLock(const std::filesystem::path &path)
Construct a file lock guard with a lock file at the given path.
Definition: filelock.cc:19
std::filesystem::path path_
Path to the file lock.
Definition: filelock.h:54
Definition: action.h:24