libutil++  1.9.3
 All Classes Functions Variables
LockFile.h
1 /*
2 ** libutil++
3 ** $Id: LockFile.h 1653 2016-02-28 19:54:59Z sella $
4 ** Copyright (c) 2011-2016 Digital Genesis, LLC. All Rights Reserved.
5 ** Released under the LGPL Version 2.1 License.
6 ** http://www.digitalgenesis.com
7 */
8 
9 #ifndef __libutilxx__sella__util__LockFile_H__
10 #define __libutilxx__sella__util__LockFile_H__
11 
12 #include "../../common.h"
13 #include "FileException.h"
14 
15 #include <limits.h>
16 #include <stdlib.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <unistd.h>
20 
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <time.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 
27 #include <string>
28 #include <mutex>
29 
30 namespace sella {
31  namespace util {
32  class LockFile;
33  }
34 }
35 
37  public:
38  static const useconds_t RetryInterval = 100000;
39 
40  public:
41  LockFile(const std::string &fullpath, useconds_t staleAge = -1, bool removeStale = true, uid_t uid = -1, gid_t gid = -1, int mode = 0644) throw ();
42  virtual ~LockFile();
43 
44  void setRemoveStale(bool on = true); /* Automatically remove stale on lock */
45  void setStaleAge(useconds_t staleAge = -1) throw (); /* Never expires */
46  void setUID(uid_t uid = -1) throw (); /* Don't change */
47  void setGID(gid_t gid = -1) throw (); /* Don't change */
48  void setMode(int mode = 0644) throw ();
49 
50  bool lock(useconds_t retryInterval = RetryInterval) throw (FileException); /* Blocking create and lock lockfile */
51  bool tryLock(void) throw (FileException); /* Attempt to create and lock lockfile */
52  bool tryLockUntil(time_t timeout, useconds_t retryInterval = RetryInterval) throw (FileException); /* Attempt to create and lock lockfile */
53  bool tryLockFor(time_t duration, useconds_t retryInterval = RetryInterval) throw (FileException); /* Attempt to create and lock lockfile */
54  bool tryLockCount(int64_t retries, useconds_t retryInterval = RetryInterval) throw (FileException); /* Blocking create and lock lockfile */
55  bool unlock(void) throw (FileException); /* Unlock and remove lockfile */
56  bool remove(void) throw (); /* Used to remove stale lock file - Will not remove locked lockfile */
57 
58  bool ownLock(void) throw ();
59  bool isLocked(void) throw ();
60  bool isStale(void) throw ();
61 
62  protected:
63  bool lock_nonblock(void) throw (FileException);
64  bool unlink(void) throw ();
65  void close(void) throw ();
66 
67  private:
68  std::string fullpath;
69  useconds_t stale;
70  bool removeStale;
71  uid_t uid;
72  gid_t gid;
73  int mode;
74  int fd;
75  std::mutex mutex;
76 };
77 
78 #endif
79 
80 /*
81 ** vim: noet ts=3 sw=3
82 */