Version: SMASH-3.1
smash::FileLock Class Reference

#include <filelock.h>

Guard to create a file lock.

This can be used to make sure concurrent processes do not interfere when for example writing files.

The lock file will be deleted when the FileLock is destroyed.

Internally this uses some POSIX system calls to atomically check for the existence of a file and create it if it does not exists. This works even over NFS (for at least NFSv3 and Linux 2.6).

Definition at line 30 of file filelock.h.

Public Member Functions

 FileLock (const std::filesystem::path &path)
 Construct a file lock guard with a lock file at the given path. More...
 
 ~FileLock ()
 Delete the lock file when the guard is destroyed. More...
 
bool acquire ()
 Try to acquire the file lock. More...
 

Private Attributes

std::filesystem::path path_
 Path to the file lock. More...
 
bool acquired_
 Whether the lock has been acquired. More...
 

Constructor & Destructor Documentation

◆ FileLock()

smash::FileLock::FileLock ( const std::filesystem::path &  path)
explicit

Construct a file lock guard with a lock file at the given path.

This will not create a file, use acquire() for that.

Parameters
[in]pathPath to file.
Returns
Constructed object.

Definition at line 19 of file filelock.cc.

20  : path_(path), acquired_(false) {}
bool acquired_
Whether the lock has been acquired.
Definition: filelock.h:56
std::filesystem::path path_
Path to the file lock.
Definition: filelock.h:54

◆ ~FileLock()

smash::FileLock::~FileLock ( )

Delete the lock file when the guard is destroyed.

Definition at line 41 of file filelock.cc.

41  {
42  if (acquired_) {
43  std::filesystem::remove(path_);
44  }
45 }

Member Function Documentation

◆ acquire()

bool smash::FileLock::acquire ( )

Try to acquire the file lock.

Returns
Returns false if the file already exists. Returns true and creates the file otherwise.
Exceptions
std::runtime_errorif called another time after returning true or if the lockfile cannot be closed.

Definition at line 22 of file filelock.cc.

22  {
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 }

Member Data Documentation

◆ path_

std::filesystem::path smash::FileLock::path_
private

Path to the file lock.

Definition at line 54 of file filelock.h.

◆ acquired_

bool smash::FileLock::acquired_
private

Whether the lock has been acquired.

Definition at line 56 of file filelock.h.


The documentation for this class was generated from the following files: