www.mooseframework.org
LockFile.C
Go to the documentation of this file.
1 //* This file is part of the MOOSE framework
2 //* https://www.mooseframework.org
3 //*
4 //* All rights reserved, see COPYRIGHT for full restrictions
5 //* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6 //*
7 //* Licensed under LGPL 2.1, please see LICENSE for details
8 //* https://www.gnu.org/licenses/lgpl-2.1.html
9 
10 #include "LockFile.h"
11 #include "MooseError.h"
12 #include <fcntl.h>
13 #include <sys/file.h>
14 #include <unistd.h>
15 
16 LockFile::LockFile(const std::string & filename, bool do_lock)
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 }
31 
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 mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:284
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition: MooseError.h:296
const std::string _filename
Definition: LockFile.h:31
int _fd
Definition: LockFile.h:30
const bool _do_lock
Definition: LockFile.h:29
~LockFile()
Definition: LockFile.C:32
LockFile(const std::string &filename, bool do_lock=true)
Definition: LockFile.C:16