Version: SMASH-2.0
filelock.cc
Go to the documentation of this file.
1 /*
2  *
3  * Copyright (c) 2014-2018
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 
16 namespace smash {
17 
18 FileLock::FileLock(const bf::path& path) : path_(path), acquired_(false) {}
19 
21  if (acquired_) {
22  throw std::runtime_error("FileLock \"" + path_.native() +
23  "\" was already acquired.");
24  }
25  // The following POSIX syscall fails if the file already exists and creates it
26  // otherwise. This is atomic, so there cannot be a race.
27  const int fd =
28  open(path_.native().c_str(), O_EXCL | O_CREAT, S_IRUSR | S_IWUSR);
29  if (fd < 0) {
30  return false;
31  }
32  acquired_ = true;
33  if (close(fd) != 0) {
34  throw std::runtime_error("Could not close file lock.");
35  }
36  return true;
37 }
38 
40  if (acquired_) {
41  bf::remove(path_);
42  }
43 }
44 
45 } // namespace smash
smash
Definition: action.h:24
smash::FileLock::acquired_
bool acquired_
Whether the lock has been acquired.
Definition: filelock.h:56
smash::FileLock::~FileLock
~FileLock()
Delete the lock file when the guard is destroyed.
Definition: filelock.cc:39
smash::FileLock::path_
bf::path path_
Path to the file lock.
Definition: filelock.h:54
smash::FileLock::FileLock
FileLock(const bf::path &path)
Construct a file lock guard with a lock file at the given path.
Definition: filelock.cc:18
filelock.h
smash::FileLock::acquire
bool acquire()
Try to acquire the file lock.
Definition: filelock.cc:20