-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathLock.cpp
More file actions
85 lines (69 loc) · 1.73 KB
/
Lock.cpp
File metadata and controls
85 lines (69 loc) · 1.73 KB
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
// Implementation of Lock class which creates a file in a directory
// with a given name which prevents the process from continuing
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include "Display.h"
#include "Lock.h"
#ifndef LOCK_DIRECTORY
#define LOCK_DIRECTORY "/tmp"
#endif
using namespace Display;
using std::cout;
using std::endl;
using std::find;
using std::list;
using std::string;
list<string> Lock::lockList;
Lock::Lock(string name)
{
const string lockDirectory = LOCK_DIRECTORY;
fileName = lockDirectory + "/" + name;
LeaderPrint("Creating lock file");
lockFile = fopen(fileName.c_str(), "r");
if (lockFile == NULL) { // the file doesn't exist, the device is free
lockFile = fopen(fileName.c_str(), "w");
if (lockFile == NULL) {
cout << ErrorStr();
perror("fopen");
exit(EXIT_FAILURE);
}
cout << InfoStr(fileName) << endl;
// store the pid of the locking process in the file
fprintf(lockFile, "%10d", getpid());
fclose(lockFile);
if (Lock::lockList.empty()) {
atexit(RemoveLocks);
}
Lock::lockList.push_back(fileName);
} else {
pid_t pid;
fscanf(lockFile, "%10d", &pid);
cout << ErrorStr() << endl;
cout << " Lockfile " << InfoStr(fileName) << " already created by process " << pid << endl;
fclose(lockFile);
exit(EXIT_FAILURE);
}
}
Lock::~Lock()
{
Remove();
}
void Lock::Remove(void)
{
Remove(fileName);
}
// static method
void Lock::Remove(std::string &name)
{
LeaderPrint("Removing lock file " + name);
Display::StatusPrint(remove(name.c_str()) < 0);
Lock::lockList.remove(name);
}
void RemoveLocks(void)
{
while (!Lock::lockList.empty()) {
Lock::Remove(Lock::lockList.front());
}
}