Version: SMASH-3.1
filelock.cc
Go to the documentation of this file.
1 /*
2  *
3  * Copyright (c) 2015,2017-2018,2022
4  * SMASH Team
5  *
6  * GNU General Public License (GPLv3 or later)
7  *
8  */
9 
10 #include "smash/filelock.h"
11 
12 #include <fcntl.h>
13 #include <sys/stat.h>
14 #include <sys/types.h>
15 #include <unistd.h>
16 
17 namespace smash {
18 
19 FileLock::FileLock(const std::filesystem::path& path)
20  : path_(path), acquired_(false) {}
21 
23  if (acquired_) {
24  throw std::runtime_error("FileLock \"" + path_.native() +
25  "\" was already acquired.");
26  }
27  // The following POSIX syscall fails if the file already exists and creates it
28  // otherwise. This is atomic, so there cannot be a race.
29  const int fd =
30  open(path_.native().c_str(), O_EXCL | O_CREAT, S_IRUSR | S_IWUSR);
31  if (fd < 0) {
32  return false;
33  }
34  acquired_ = true;
35  if (close(fd) != 0) {
36  throw std::runtime_error("Could not close file lock.");
37  }
38  return true;
39 }
40 
42  if (acquired_) {
43  std::filesystem::remove(path_);
44  }
45 }
46 
47 } // namespace smash
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