1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2019 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 // http://www.gnu.org/licenses/lgpl-2.1.txt
20 //////////////////////////////////////////////////////////////////////////////////
25 #include <MUtils/Global.h>
34 ///////////////////////////////////////////////////////////////////////////////
36 ///////////////////////////////////////////////////////////////////////////////
42 class DirLockException
: public std::runtime_error
45 DirLockException(const char *const message
)
47 std::runtime_error(message
)
55 DirLock(const QString dirPath
)
60 const QByteArray testData
= QByteArray(TEST_DATA
);
61 if(m_dirPath
.isEmpty())
63 throw DirLockException("Path must not be empty!");
65 for(int i
= 0; i
< 32; i
++)
67 m_lockFile
.reset(new QFile(QString("%1/~%2.lck").arg(m_dirPath
, MUtils::next_rand_str())));
68 if(m_lockFile
->open(QIODevice::WriteOnly
| QIODevice::Truncate
| QIODevice::Unbuffered
))
70 if(m_lockFile
->write(testData
) >= testData
.size())
72 if(m_lockFile
->error() == QFile::NoError
)
83 throw DirLockException("Locking has failed!");
90 if(!m_lockFile
.isNull())
92 for(int i
= 0; i
< 16; i
++)
94 if(m_lockFile
->remove() || (!m_lockFile
->exists()))
104 qWarning("DirLock: The lock file could not be removed!");
108 inline const QString
&getPath(void) const
114 static const char *const TEST_DATA
;
115 const QString m_dirPath
;
116 QScopedPointer
<QFile
> m_lockFile
;
119 const char *const DirLock::TEST_DATA
= "7QtDxPWotHGQYv1xHyQHFKjTB5u5VYKHE20NMDAgLRYoy16CZN7mEYijbjCJpORnoBbtHCzqyy1a6BLCMMiTUZpLzgjg4qnN505egUBqk3wMhPsYjFpkng9i37mWd1iF";