utils/snapshot: Don't remove utils/syncviewer from snapshots
[skype-call-recorder.git] / utils.cpp
blobaaacfee13868a1ec1260b469446c4dbff55103cb
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 debug("ERROR: cannot get lock on lock file");
55 return false;
58 // set the FD_CLOEXEC flag, so that when another process forks off of
59 // us, it won't inherit the file descriptor and the lock. see commit
60 // ce6f838b4587528630784c1ea1ad272b64e78544 to see why we do this
62 int flags = fcntl(fd, F_GETFD, 0);
64 if (flags == -1) {
65 debug("ERROR: failed to fcntl() lock file");
66 unlock();
67 return false;
70 flags |= FD_CLOEXEC;
71 flags = fcntl(fd, F_SETFD, flags);
73 if (flags == -1) {
74 debug("ERROR: failed to set FD_CLOEXEC on lock file");
75 unlock();
76 return false;
79 debug("Got lock on lock file");
80 return true;
83 void LockFile::unlock() {
84 if (!isLocked())
85 return;
86 QFile::remove(fileName);
87 flock(fd, LOCK_UN);
88 close(fd);
89 fd = -1;
92 bool LockFile::isLocked() const {
93 return fd >= 0;