www.mooseframework.org
Public Member Functions | Protected Attributes | List of all members
LockFile Class Reference

Gets an exclusive lock on a file. More...

#include <LockFile.h>

Public Member Functions

 LockFile (const std::string &filename, bool do_lock=true)
 
 ~LockFile ()
 

Protected Attributes

const bool _do_lock
 
int _fd
 
const std::string _filename
 

Detailed Description

Gets an exclusive lock on a file.

This uses RAII to obtain the lock in the constructor and release the lock in the destructor. Additionally, to allow for easier use as a stack variable, an optional bool is allowed to specify that no locking is actually done. This is useful for the case where only certain processors need to obtain the lock.

Definition at line 23 of file LockFile.h.

Constructor & Destructor Documentation

◆ LockFile()

LockFile::LockFile ( const std::string &  filename,
bool  do_lock = true 
)

Definition at line 16 of file LockFile.C.

17  : _do_lock(do_lock), _fd(-1), _filename(filename)
18 {
19  if (_do_lock)
20  {
21  _fd = open(filename.c_str(), O_RDWR | O_CREAT, 0666);
22  if (_fd == -1)
23  mooseError("Failed to open file", filename);
24  if (flock(_fd, LOCK_EX) != 0)
25  mooseWarning("Failed to lock file ", filename);
26  }
27 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:208
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition: MooseError.h:220
const std::string _filename
Definition: LockFile.h:32
int _fd
Definition: LockFile.h:31
const bool _do_lock
Definition: LockFile.h:30

◆ ~LockFile()

LockFile::~LockFile ( )

Definition at line 29 of file LockFile.C.

30 {
31  if (_do_lock)
32  {
33  if (flock(_fd, LOCK_UN) != 0)
34  mooseWarning("Failed to unlock file ", _filename);
35  close(_fd);
36  }
37 }
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition: MooseError.h:220
const std::string _filename
Definition: LockFile.h:32
int _fd
Definition: LockFile.h:31
the_pc close()
const bool _do_lock
Definition: LockFile.h:30

Member Data Documentation

◆ _do_lock

const bool LockFile::_do_lock
protected

Definition at line 30 of file LockFile.h.

Referenced by LockFile(), and ~LockFile().

◆ _fd

int LockFile::_fd
protected

Definition at line 31 of file LockFile.h.

Referenced by LockFile(), and ~LockFile().

◆ _filename

const std::string LockFile::_filename
protected

Definition at line 32 of file LockFile.h.

Referenced by ~LockFile().


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