2 * Worldvisions Weaver Software:
3 * Copyright (C) 1997-2002 Net Integration Technologies, Inc.
5 * Some handy functions to create/remove /var/lock lockfiles.
12 #include <sys/types.h>
17 WvLockDev::WvLockDev(WvString _devicename
)
18 : devicename(_devicename
)
20 const char *p
= strrchr(devicename
, '/');
27 filename
= WvString("/var/lock/LCK..%s", p
);
31 WvLockDev::~WvLockDev()
41 #if USE_LOCKDEV /* use the liblockdev.a locking routines */
45 bool WvLockDev::lock()
53 if (dev_lock(devicename
))
61 void WvLockDev::unlock()
63 if (!lock_count
) return;
66 dev_unlock(devicename
, getpid());
70 #else /* !USE_LOCKDEV -- implement our own locking routines */
73 // note: this function uses the O_EXCL flag to open(), and thus assumes
74 // that /var/lock is not an NFS-mounted drive (according to the open() man
75 // page, you need to follow a special procedure to ensure successful NFS
78 // Actually there may be other race conditions that we should look into.
79 bool WvLockDev::lock()
89 WvFile
fd(filename
, O_RDWR
| O_EXCL
| O_CREAT
, 0644);
93 // We made a lock file...
94 fd
.print("%10s\n", getpid());
96 else if (fd
.geterr() == EEXIST
)
100 // Lock file is already there! Check for staleness...
101 sleep(1); // preventing race condition...
103 fd
.open(filename
, O_RDONLY
);
104 //fprintf(stderr, "ok: %d\n", fd.isok());
105 inbuf
= trim_string(fd
.blocking_getline(-1));
106 //fprintf(stderr, "blocking_getline: '%s'\n", inbuf);
113 //fprintf(stderr, "pid: '%d'\n", pid);
115 if (pid
&& pid
!= -1 && kill(pid
, 0) == -1 && errno
== ESRCH
)
117 // we can create a lockfile now
119 if (unlink(filename
))
120 return false; // cannot remove lockfile
121 fd
.open(filename
, O_RDWR
| O_EXCL
| O_CREAT
, 0644);
122 fd
.print("%10s\n", getpid());
125 return false; // device already locked
127 else // some other unexpected error
136 void WvLockDev::unlock()
138 if (!lock_count
) return;
145 #endif /* !USE_LOCKDEV */