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 22 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 // for now just do not do any locking on Windows
20 #ifndef __WIN32__
21  if (_do_lock)
22  {
23  _fd = open(filename.c_str(), O_RDWR | O_CREAT, 0666);
24  if (_fd == -1)
25  mooseError("Failed to open file", filename);
26  if (flock(_fd, LOCK_EX) != 0)
27  mooseWarning("Failed to lock file ", filename);
28  }
29 #endif
30 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:299
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition: MooseError.h:333
const std::string _filename
Definition: LockFile.h:31
int _fd
Definition: LockFile.h:30
const bool _do_lock
Definition: LockFile.h:29

◆ ~LockFile()

LockFile::~LockFile ( )

Definition at line 32 of file LockFile.C.

33 {
34 #ifndef __WIN32__
35  if (_do_lock)
36  {
37  if (flock(_fd, LOCK_UN) != 0)
38  mooseWarning("Failed to unlock file ", _filename);
39  close(_fd);
40  }
41 #endif
42 }
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition: MooseError.h:333
const std::string _filename
Definition: LockFile.h:31
int _fd
Definition: LockFile.h:30
const bool _do_lock
Definition: LockFile.h:29

Member Data Documentation

◆ _do_lock

const bool LockFile::_do_lock
protected

Definition at line 29 of file LockFile.h.

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

◆ _fd

int LockFile::_fd
protected

Definition at line 30 of file LockFile.h.

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

◆ _filename

const std::string LockFile::_filename
protected

Definition at line 31 of file LockFile.h.

Referenced by ~LockFile().


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