LP-551 Changes from review, change names and fix typos.
[librepilot.git] / ground / gcs / src / shared / qtlockedfile / qtlockedfile_unix.cpp
blobe0a460daf58ccf355b62bcfe6cd7063321d81683
1 /**
2 ******************************************************************************
4 * @file qtlockedfile_unix.cpp
5 * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
6 * Parts by Nokia Corporation (qt-info@nokia.com) Copyright (C) 2009.
7 * @brief
8 * @see The GNU Public License (GPL) Version 3
9 * @defgroup
10 * @{
12 *****************************************************************************/
14 * This program is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 3 of the License, or
17 * (at your option) any later version.
19 * This program is distributed in the hope that it will be useful, but
20 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
21 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 * for more details.
24 * You should have received a copy of the GNU General Public License along
25 * with this program; if not, write to the Free Software Foundation, Inc.,
26 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29 #include "qtlockedfile.h"
31 #include <string.h>
32 #include <errno.h>
33 #include <unistd.h>
34 #include <fcntl.h>
36 namespace SharedTools {
37 bool QtLockedFile::lock(LockMode mode, bool block)
39 if (!isOpen()) {
40 qWarning("QtLockedFile::lock(): file is not opened");
41 return false;
44 if (mode == NoLock) {
45 return unlock();
48 if (mode == m_lock_mode) {
49 return true;
52 if (m_lock_mode != NoLock) {
53 unlock();
56 struct flock fl;
57 fl.l_whence = SEEK_SET;
58 fl.l_start = 0;
59 fl.l_len = 0;
60 fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK;
61 int cmd = block ? F_SETLKW : F_SETLK;
62 int ret = fcntl(handle(), cmd, &fl);
64 if (ret == -1) {
65 if (errno != EINTR && errno != EAGAIN) {
66 qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno));
68 return false;
72 m_lock_mode = mode;
73 return true;
77 bool QtLockedFile::unlock()
79 if (!isOpen()) {
80 qWarning("QtLockedFile::unlock(): file is not opened");
81 return false;
84 if (!isLocked()) {
85 return true;
88 struct flock fl;
89 fl.l_whence = SEEK_SET;
90 fl.l_start = 0;
91 fl.l_len = 0;
92 fl.l_type = F_UNLCK;
93 int ret = fcntl(handle(), F_SETLKW, &fl);
95 if (ret == -1) {
96 qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno));
97 return false;
100 m_lock_mode = NoLock;
101 return true;
104 QtLockedFile::~QtLockedFile()
106 if (isOpen()) {
107 unlock();
110 } // namespace SharedTools