-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocks.cpp
79 lines (59 loc) · 1.41 KB
/
locks.cpp
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
#include "partoss.h"
#include "globext.h"
#include "locks.h"
#include <sys/types.h>
#include <signal.h>
int readlock (char * filename)
{
int h, pid;
char apid[20]; // ascii lock
int length;
if ((h = open(filename, O_RDONLY)) == -1)
return -1; // open error
length = read(h, apid, sizeof(apid) - 1);
apid[length] = 0;
pid = 0;
if ((length == sizeof(pid)) || (sscanf(apid, "%d", &pid) != 1) || (pid == 0))
pid = *((int *)apid); // ? binary lock
close(h);
return pid; // success
};
int writelock (char * filename)
{
int h;
char apid[16];
if ((h = open(filename, O_CREAT|O_WRONLY|O_EXCL, 0644)) == -1)
return -1; // create error
sprintf(apid, "%10d\n", getpid());
if (write(h, apid, strlen(apid)) != strlen(apid))
{
close(h);
return -1; // write error
};
close(h);
return 0; // success
};
int checklock (char * filename)
{
int pid;
struct stat st;
if ((stat(filename, &st) == -1) && errno == ENOENT)
return 0; // no file
if ((pid = readlock(filename)) == -1)
return 0; // read error
if (pid == getpid())
return 0; // ! our lock
if ((kill(pid, 0) == -1) && errno == ESRCH)
{
unlink(filename);
return 0; // no owner
};
return pid; // success
};
int removelock (char * filename)
{
if (lck)
if (unlink(filename) != -1)
return 0; // success
return -1; // error
};