File: wvlockfile.cc

package info (click to toggle)
wvstreams 4.6.1-19
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,420 kB
  • sloc: cpp: 64,196; ansic: 4,154; sh: 4,025; makefile: 546; perl: 402
file content (84 lines) | stat: -rw-r--r-- 1,440 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
 * Worldvisions Weaver Software:
 *   Copyright (C) 1997-2002 Net Integration Technologies, Inc.
 * 
 * A simple lockfile class using WvStreams.
 */

#include "wvlockfile.h"
#include "strutils.h"
#include <signal.h>


WvLockFile::WvLockFile(WvStringParm _lockname)
    : lockname(_lockname)
{
    // nothing special
}


bool WvLockFile::isok()
{
    pid_t pid = readpid();
    return !pid || pid == getpid();
}


bool WvLockFile::lock()
{
    if (!isok())
        return false;

    WvFile lock(lockname, O_WRONLY|O_CREAT|O_EXCL);
    if (!lock.isok())
        return false;

    lock.print("%s\n", getpid());
    return true;
}


bool WvLockFile::unlock()
{
    if (!isok())
	return false;

    unlink(lockname);

    return readpid() == 0;
}


pid_t WvLockFile::readpid()
{
    char *line;
    pid_t pid = 0;
    WvString lockdir(getdirname(lockname));

    if (access(lockdir, W_OK) < 0 
      || (!access(lockname, F_OK) && access(lockname, R_OK) < 0))
	return -1; // won't be able to create a lock
    else
    {
        WvFile lock(lockname, O_RDONLY);
	line = lock.blocking_getline(-1);
	if (line)
	{
	    pid = atoi(line);
	    if (pid != -1 && kill(pid, 0) < 0 && errno == ESRCH) // no such process
	    {
		// previous lock owner is dead; clean it up.
		::unlink(lockname);
		return 0;
	    }
	}
        else
        {
		// blank lock file; clean it up.
		::unlink(lockname);
		return 0;
        }
    }
    
    return pid;
}