-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathfile_lock.cpp
More file actions
53 lines (49 loc) · 1.07 KB
/
Copy pathfile_lock.cpp
File metadata and controls
53 lines (49 loc) · 1.07 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
#include <string>
#include <sys/file.h>
#include "log.h"
#include "common.h"
#include "file_lock.h"
FileLock::FileLock(const std::string_view path, int operation) : held_(false)
{
fd_ = open(path.data(), O_CREAT | O_RDONLY, 0); // the perm of lock file is 0600
if (fd_ == -1) {
return;
}
Aquire(operation);
}
bool FileLock::Aquire(int operation)
{
/*
* (1) The flock can block when anyone else holding the lock;
* (2) The flock can be released either by calling the LOCK_UN parameter or
* by closing fd (the first parameter in flock), which means that flock
* is automatically released when the process is exited.
*/
int ret = flock(fd_, operation);
if (ret) {
return false;
}
held_ = true;
return true;
}
bool FileLock::Release()
{
int ret = flock(fd_, LOCK_UN);
if (ret) {
return false;
}
held_ = false;
return true;
}
FileLock::~FileLock()
{
if (fd_ < 0) {
return;
}
if (held_) {
Release();
}
if (close(fd_) == -1) {
return;
}
}