Krita Source Code Documentation
Loading...
Searching...
No Matches
qtlockedfile_unix.cpp
Go to the documentation of this file.
1// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
2// SPDX-License-Identifier: BSD-3-Clause
3
4#include <string.h>
5#include <errno.h>
6#include <unistd.h>
7#include <fcntl.h>
8
9#include "qtlockedfile.h"
10
11bool QtLockedFile::lock(LockMode mode, bool block)
12{
13 if (!isOpen()) {
14 qWarning("QtLockedFile::lock(): file is not opened");
15 return false;
16 }
17
18 if (mode == NoLock)
19 return unlock();
20
21 if (mode == m_lock_mode)
22 return true;
23
24 if (m_lock_mode != NoLock)
25 unlock();
26
27 struct flock fl;
28 fl.l_whence = SEEK_SET;
29 fl.l_start = 0;
30 fl.l_len = 0;
31 fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK;
32 int cmd = block ? F_SETLKW : F_SETLK;
33 int ret = fcntl(handle(), cmd, &fl);
34
35 if (ret == -1) {
36 if (errno != EINTR && errno != EAGAIN)
37 qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno));
38 return false;
39 }
40
41
42 m_lock_mode = mode;
43 return true;
44}
45
46
47bool QtLockedFile::unlock()
48{
49 if (!isOpen()) {
50 qWarning("QtLockedFile::unlock(): file is not opened");
51 return false;
52 }
53
54 if (!isLocked())
55 return true;
56
57 struct flock fl;
58 fl.l_whence = SEEK_SET;
59 fl.l_start = 0;
60 fl.l_len = 0;
61 fl.l_type = F_UNLCK;
62 int ret = fcntl(handle(), F_SETLKW, &fl);
63
64 if (ret == -1) {
65 qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno));
66 return false;
67 }
68
69 m_lock_mode = NoLock;
70 return true;
71}
72
73QtLockedFile::~QtLockedFile()
74{
75 if (isOpen())
76 unlock();
77}
78