-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpidfile.cpp
More file actions
67 lines (49 loc) · 1.12 KB
/
Copy pathpidfile.cpp
File metadata and controls
67 lines (49 loc) · 1.12 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
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
class pidFile {
public:
pidFile() { }
~pidFile() { }
int setPidFile(std::string fileName)
{
int ret;
fd_ = open(fileName.c_str(), O_RDWR);
if (fd_ < 0) {
return -1;
}
ret = lockf(fd_, F_TLOCK, 0);
if (ret< 0) {
return -1;
}
return 0;
}
int removePidFile()
{
lockf(fd_, F_ULOCK, 0);
close(fd_);
return 0;
}
private:
int fd_;
};
int main(int argc, char **argv)
{
pidFile p;
int ret;
if (argc != 2) {
std::cerr << argv[0] << " filename" << std::endl;
return -1;
}
ret = p.setPidFile(std::string(argv[1]));
if (ret < 0) {
std::cerr << "failed to acquire lock " << std::endl;
return -1;
}
std::cout << "lock acquired successfully" << std::endl;
// run another process and test locking..
while (1);
return 0;
}