-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathutils.cpp
96 lines (76 loc) · 2.25 KB
/
utils.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
Skype Call Recorder
Copyright 2008-2010, 2013, 2015 by jlh (jlh at gmx dot ch)
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
The GNU General Public License version 2 is included with the source of
this program under the file name COPYING. You can also get a copy on
http://www.fsf.org/
*/
#include <QFile>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "utils.h"
#include "common.h"
LockFile::LockFile() :
fd(-1)
{
}
LockFile::~LockFile() {
unlock();
}
bool LockFile::lock(const QString &fn) {
fileName = fn;
fd = open(QFile::encodeName(fileName).constData(), O_CREAT | O_WRONLY, 0644);
if (fd < 0) {
debug("ERROR: opening lock file failed");
return false;
}
if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
close(fd);
fd = -1;
debug("ERROR: cannot get lock on lock file");
return false;
}
// set the FD_CLOEXEC flag, so that when another process forks off of
// us, it won't inherit the file descriptor and the lock. see commit
// ce6f838b4587528630784c1ea1ad272b64e78544 to see why we do this
int flags = fcntl(fd, F_GETFD, 0);
if (flags == -1) {
debug("ERROR: failed to fcntl() lock file");
unlock();
return false;
}
flags |= FD_CLOEXEC;
flags = fcntl(fd, F_SETFD, flags);
if (flags == -1) {
debug("ERROR: failed to set FD_CLOEXEC on lock file");
unlock();
return false;
}
debug("Got lock on lock file");
return true;
}
void LockFile::unlock() {
if (!isLocked())
return;
QFile::remove(fileName);
flock(fd, LOCK_UN);
close(fd);
fd = -1;
}
bool LockFile::isLocked() const {
return fd >= 0;
}