Reduce risks of lock file corruption

Trying to do as few operations as possible once the file got opened.
That includes generating the data which will go in the file. Indeed if
we crashed at that point the lock file is already emptied. Could happen
because of the qAppName call. It's then safer to prepare the data
upfront, and just open/write/close if possible.

Change-Id: Iad32fa822c6a5958ae89d84a2fe02ed5366ea278
Reviewed-by: Jędrzej Nowacki <jedrzej.nowacki@digia.com>
Reviewed-by: Frederik Gladhorn <frederik.gladhorn@digia.com>
This commit is contained in:
Kevin Ottens 2013-10-09 13:12:11 +02:00 committed by The Qt Project
parent 059857d4d5
commit d8d6880682

View File

@ -140,6 +140,16 @@ static bool setNativeLocks(int fd)
QLockFile::LockError QLockFilePrivate::tryLock_sys()
{
// Assemble data, to write in a single call to write
// (otherwise we'd have to check every write call)
QByteArray fileData;
fileData += QByteArray::number(QCoreApplication::applicationPid());
fileData += '\n';
fileData += qAppName().toUtf8();
fileData += '\n';
fileData += localHostName().toUtf8();
fileData += '\n';
const QByteArray lockFileName = QFile::encodeName(fileName);
const int fd = qt_safe_open(lockFileName.constData(), O_WRONLY | O_CREAT | O_EXCL, 0644);
if (fd < 0) {
@ -160,16 +170,6 @@ QLockFile::LockError QLockFilePrivate::tryLock_sys()
// We hold the lock, continue.
fileHandle = fd;
// Assemble data, to write in a single call to write
// (otherwise we'd have to check every write call)
QByteArray fileData;
fileData += QByteArray::number(QCoreApplication::applicationPid());
fileData += '\n';
fileData += qAppName().toUtf8();
fileData += '\n';
fileData += localHostName().toUtf8();
fileData += '\n';
QLockFile::LockError error = QLockFile::NoError;
if (qt_write_loop(fd, fileData.constData(), fileData.size()) < fileData.size())
error = QLockFile::UnknownError; // partition full