Logo ROOT   6.30.04
Reference Guide
 All Namespaces Files Pages
TLockPath.cxx
Go to the documentation of this file.
1 // @(#)root/proof:$Id$
2 // Author: G. Ganis, Oct 2011
3 
4 /*************************************************************************
5  * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
6  * All rights reserved. *
7  * *
8  * For the licensing terms see $ROOTSYS/LICENSE. *
9  * For the list of contributors see $ROOTSYS/README/CREDITS. *
10  *************************************************************************/
11 
12 /** \class TLockPath
13 \ingroup proofkernel
14 
15 Path locking class allowing shared and exclusive locks
16 
17 */
18 
19 #include "TLockPath.h"
20 #include "TSystem.h"
21 #if defined(R__WIN32) && !defined(R__WINGCC)
22 #include <io.h>
23 #define lseek _lseek
24 #define close _close
25 #define open _open
26 #define O_CREAT _O_CREAT
27 #define O_RDWR _O_RDWR
28 #else
29 #include <sys/file.h>
30 #endif
31 
32 ////////////////////////////////////////////////////////////////////////////////
33 /// Locks the directory. Waits if lock is hold by an other process.
34 /// Returns 0 on success, -1 in case of error.
35 
36 TLockPath::TLockPath(const char *path) : fName(path), fLockId(-1)
37 {
38  // Work with full names
39  if (gSystem->ExpandPathName(fName))
40  Warning("TLockPath", "problems expanding path '%s'", fName.Data());
41 }
42 
43 Int_t TLockPath::Lock(Bool_t shared)
44 {
45  const char *pname = GetName();
46 
47  if (gSystem->AccessPathName(pname))
48  fLockId = open(pname, O_CREAT | O_RDWR, 0644);
49  else
50  fLockId = open(pname, O_RDWR);
51 
52  if (fLockId == -1) {
53  SysError("Lock", "cannot open lock file %s", pname);
54  return -1;
55  }
56 
57  if (gDebug > 1)
58  Info("Lock", "%d: locking file %s ...", gSystem->GetPid(), pname);
59  // lock the file
60 #if !defined(R__WIN32) && !defined(R__WINGCC)
61  int op = (shared) ? LOCK_SH : LOCK_EX ;
62  if (flock(fLockId, op) == -1) {
63  SysError("Lock", "error locking %s", pname);
64  close(fLockId);
65  fLockId = -1;
66  return -1;
67  }
68 #endif
69 
70  if (gDebug > 1)
71  Info("Lock", "%d: file %s locked", gSystem->GetPid(), pname);
72 
73  return 0;
74 }
75 
76 ////////////////////////////////////////////////////////////////////////////////
77 /// Unlock the directory. Returns 0 in case of success,
78 /// -1 in case of error.
79 
80 Int_t TLockPath::Unlock()
81 {
82  if (!IsLocked())
83  return 0;
84 
85  if (gDebug > 1)
86  Info("Unlock", "%d: unlocking file %s ...", gSystem->GetPid(), GetName());
87  // unlock the file
88  lseek(fLockId, 0, SEEK_SET);
89 #if !defined(R__WIN32) && !defined(R__WINGCC)
90  if (flock(fLockId, LOCK_UN) == -1) {
91  SysError("Unlock", "error unlocking %s", GetName());
92  close(fLockId);
93  fLockId = -1;
94  return -1;
95  }
96 #endif
97 
98  if (gDebug > 1)
99  Info("Unlock", "%d: file %s unlocked", gSystem->GetPid(), GetName());
100 
101  close(fLockId);
102  fLockId = -1;
103 
104  return 0;
105 }