WvStreams
wvlockfile.cc
1/*
2 * Worldvisions Weaver Software:
3 * Copyright (C) 1997-2002 Net Integration Technologies, Inc.
4 *
5 * A simple lockfile class using WvStreams.
6 */
7
8#include "wvlockfile.h"
9#include "strutils.h"
10#include <signal.h>
11
12
13WvLockFile::WvLockFile(WvStringParm _lockname)
14 : lockname(_lockname)
15{
16 // nothing special
17}
18
19
21{
22 pid_t pid = readpid();
23 return !pid || pid == getpid();
24}
25
26
28{
29 if (!isok())
30 return false;
31
32 WvFile lock(lockname, O_WRONLY|O_CREAT|O_EXCL);
33 if (!lock.isok())
34 return false;
35
36 lock.print("%s\n", getpid());
37 return true;
38}
39
40
42{
43 if (!isok())
44 return false;
45
46 unlink(lockname);
47
48 return readpid() == 0;
49}
50
51
53{
54 char *line;
55 pid_t pid = 0;
56 WvString lockdir(getdirname(lockname));
57
58 if (access(lockdir, W_OK) < 0
59 || (!access(lockname, F_OK) && access(lockname, R_OK) < 0))
60 return -1; // won't be able to create a lock
61 else
62 {
63 WvFile lock(lockname, O_RDONLY);
64 line = lock.blocking_getline(-1);
65 if (line)
66 {
67 pid = atoi(line);
68 if (pid != -1 && kill(pid, 0) < 0 && errno == ESRCH) // no such process
69 {
70 // previous lock owner is dead; clean it up.
71 ::unlink(lockname);
72 return 0;
73 }
74 }
75 else
76 {
77 // blank lock file; clean it up.
78 ::unlink(lockname);
79 return 0;
80 }
81 }
82
83 return pid;
84}
A WvFastString acts exactly like a WvString, but can take (const char *) strings without needing to a...
Definition wvstring.h:94
WvFile implements a stream connected to a file or Unix device.
Definition wvfile.h:29
pid_t readpid()
Returns one of three things: -1 if the lockfile exists, but is inaccessible.
Definition wvlockfile.cc:52
bool lock()
Creates the lockfile with the current pid.
Definition wvlockfile.cc:27
bool unlock()
Removes the lockfile if present.
Definition wvlockfile.cc:41
bool isok()
Check to make sure no lock is established or that it's owned by us.
Definition wvlockfile.cc:20
WvString is an implementation of a simple and efficient printable-string class.
Definition wvstring.h:330