Line data Source code
1 : /**
2 : * Author/Copyright: Jorg Preiss
3 : *
4 : * @license MIT
5 : *
6 : * Permission is hereby granted, free of charge, to any person obtaining
7 : * a copy of this software and associated documentation files (the
8 : * "Software"), to deal in the Software without restriction, including
9 : * without limitation the rights to use, copy, modify, merge, publish,
10 : * distribute, sublicense, and/or sell copies of the Software, and to
11 : * permit persons to whom the Software is furnished to do so, subject to
12 : * the following conditions:
13 : *
14 : * The above copyright notice and this permission notice shall be
15 : * included in all copies or substantial portions of the Software.
16 : *
17 : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 : * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 : * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 : * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 : * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 : * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 : * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 : */
25 : #pragma once
26 :
27 : #include <QFile>
28 : #include <sys/file.h>
29 :
30 0 : class QLockFile
31 : : public QFile
32 : {
33 : public:
34 : /** \brief Initialize the locked file.
35 : *
36 : * This function initializes a default locked file.
37 : */
38 : QLockFile()
39 : : QFile()
40 : {
41 : }
42 :
43 : /** \brief Initialize the locked file with a name.
44 : *
45 : * This function initializes a locked file with a filename.
46 : *
47 : * \param[in] name The name of the file to open and lock.
48 : */
49 0 : QLockFile(QString const & name)
50 0 : : QFile(name)
51 : {
52 0 : }
53 :
54 : /** \brief Open the locked file
55 : *
56 : * Open a file and lock it in share mode (if iomode is read) or
57 : * exclusively (any other open mode.)
58 : *
59 : * The function blocks until the file is locked.
60 : *
61 : * When the file is closed the lock is automatically released. The
62 : * lock can't be removed untile your close the file.
63 : *
64 : * \param[in] iomode The I/O mode to use on the file.
65 : *
66 : * \return true if the open() succeeds, false otherwise
67 : */
68 0 : virtual bool open(OpenMode iomode)
69 : {
70 0 : if(!QFile::open(iomode))
71 : {
72 0 : return false;
73 : }
74 : // we want to ignore the text and unbuffered flags
75 0 : OpenMode const m(iomode & ~(QIODevice::Text | QIODevice::Unbuffered));
76 0 : int const op(m == QIODevice::ReadOnly ? LOCK_SH : LOCK_EX);
77 : // note: on close() the flock() is automatically released
78 0 : if(flock(handle(), op) != 0)
79 : {
80 0 : QFile::close();
81 0 : return false;
82 : }
83 : // this file is now open with a lock
84 0 : return true;
85 : }
86 : };
87 :
88 : // vim: ts=4 sw=4 et
|