QLockFile::LockError QLockFilePrivate::tryLock_sys() { // Assemble data, to write in a single call to write // (otherwise we'd have to check every write call) // Use operator% from the fast builder to avoid multiple memory allocations. QByteArray fileData = QByteArray::number(QCoreApplication::applicationPid()) + '\n' + qAppName().toUtf8() + '\n' + localHostName().toUtf8() + '\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) { switch (errno) { case EEXIST: return QLockFile::LockFailedError; case EACCES: case EROFS: return QLockFile::PermissionError; default: return QLockFile::UnknownError; } } // Ensure nobody else can delete the file while we have it if (!setNativeLocks(fd)) qWarning() << "setNativeLocks failed:" << strerror(errno); // We hold the lock, continue. fileHandle = fd; QLockFile::LockError error = QLockFile::NoError; if (qt_write_loop(fd, fileData.constData(), fileData.size()) < fileData.size()) error = QLockFile::UnknownError; // partition full return error; }
bool QLockFilePrivate::removeStaleLock() { const QByteArray lockFileName = QFile::encodeName(fileName); const int fd = qt_safe_open(lockFileName.constData(), O_WRONLY, 0644); if (fd < 0) // gone already? return false; bool success = setNativeLocks(fd) && (::unlink(lockFileName) == 0); close(fd); return success; }
QLockFile::LockError QLockFilePrivate::tryLock_sys() { // Assemble data, to write in a single call to write // (otherwise we'd have to check every write call) // Use operator% from the fast builder to avoid multiple memory allocations. QByteArray fileData = QByteArray::number(QCoreApplication::applicationPid()) % '\n' % QCoreApplication::applicationName().toUtf8() % '\n' % localHostName() % '\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) { switch (errno) { case EEXIST: return QLockFile::LockFailedError; case EACCES: case EROFS: return QLockFile::PermissionError; default: return QLockFile::UnknownError; } } // Ensure nobody else can delete the file while we have it if (!setNativeLocks(fileName, fd)) { const int errnoSaved = errno; qWarning() << "setNativeLocks failed:" << qt_error_string(errnoSaved); } if (qt_write_loop(fd, fileData.constData(), fileData.size()) < fileData.size()) { close(fd); if (!QFile::remove(fileName)) qWarning("QLockFile: Could not remove our own lock file %s.", qPrintable(fileName)); return QLockFile::UnknownError; // partition full } // We hold the lock, continue. fileHandle = fd; // Sync to disk if possible. Ignore errors (e.g. not supported). #if defined(_POSIX_SYNCHRONIZED_IO) && _POSIX_SYNCHRONIZED_IO > 0 fdatasync(fileHandle); #else fsync(fileHandle); #endif return QLockFile::NoError; }