utils/makerpm: Fix building of RPMs
[skype-call-recorder.git] / utils.cpp
blobf95f0f0be6cf9490a02279c99fbf00d10d08e903
1 /*
2 Skype Call Recorder
3 Copyright (C) 2008 jlh (jlh at gmx dot ch)
5 This program is free software; you can redistribute it and/or modify it
6 under the terms of the GNU General Public License as published by the
7 Free Software Foundation; either version 2 of the License, version 3 of
8 the License, or (at your option) any later version.
10 This program is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 The GNU General Public License version 2 is included with the source of
20 this program under the file name COPYING. You can also get a copy on
21 http://www.fsf.org/
24 #include <QFile>
25 #include <sys/file.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <fcntl.h>
29 #include <unistd.h>
31 #include "utils.h"
32 #include "common.h"
34 LockFile::LockFile() :
35 fd(-1)
39 LockFile::~LockFile() {
40 unlock();
43 bool LockFile::lock(const QString &fn) {
44 fileName = fn;
45 fd = open(QFile::encodeName(fileName).constData(), O_CREAT | O_WRONLY, 0644);
47 if (fd < 0) {
48 debug("ERROR: opening lock file failed");
49 return false;
52 if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
53 close(fd);
54 fd = -1;
55 debug("ERROR: cannot get lock on lock file");
56 return false;
59 // set the FD_CLOEXEC flag, so that when another process forks off of
60 // us, it won't inherit the file descriptor and the lock. see commit
61 // ce6f838b4587528630784c1ea1ad272b64e78544 to see why we do this
63 int flags = fcntl(fd, F_GETFD, 0);
65 if (flags == -1) {
66 debug("ERROR: failed to fcntl() lock file");
67 unlock();
68 return false;
71 flags |= FD_CLOEXEC;
72 flags = fcntl(fd, F_SETFD, flags);
74 if (flags == -1) {
75 debug("ERROR: failed to set FD_CLOEXEC on lock file");
76 unlock();
77 return false;
80 debug("Got lock on lock file");
81 return true;
84 void LockFile::unlock() {
85 if (!isLocked())
86 return;
87 QFile::remove(fileName);
88 flock(fd, LOCK_UN);
89 close(fd);
90 fd = -1;
93 bool LockFile::isLocked() const {
94 return fd >= 0;