@@ -698,8 +698,14 @@ Utility::Handle lockFile(const QString &fileName, FileSystem::LockMode mode)
698698 DWORD attr = GetFileAttributesW (reinterpret_cast <const wchar_t *>(fName .utf16 ()));
699699 if (attr != INVALID_FILE_ATTRIBUTES ) {
700700 // Try to open the file with as much access as possible..
701- auto out = Utility::Handle{CreateFileW (reinterpret_cast <const wchar_t *>(fName .utf16 ()), accessMode, shareMode, nullptr , OPEN_EXISTING ,
702- FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS , nullptr )};
701+ const auto createFileResult = CreateFileW (reinterpret_cast <const wchar_t *>(fName .utf16 ()), accessMode, shareMode, nullptr , OPEN_EXISTING ,
702+ FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS , nullptr );
703+
704+ if (createFileResult == INVALID_HANDLE_VALUE ) {
705+ return {};
706+ }
707+
708+ auto out = Utility::Handle{createFileResult};
703709
704710 if (out) {
705711 if (attr & FILE_ATTRIBUTE_DIRECTORY ) {
@@ -713,9 +719,6 @@ Utility::Handle lockFile(const QString &fileName, FileSystem::LockMode mode)
713719 LARGE_INTEGER end;
714720 end.QuadPart = -1 ;
715721 if (LockFile (out.handle (), start.LowPart , start.HighPart , end.LowPart , end.HighPart )) {
716- // Lock acquired -> release it immediately
717- // just closing a file handle does not immediately release the lock leading to system instability
718- UnlockFile (out.handle (), start.LowPart , start.HighPart , end.LowPart , end.HighPart );
719722 return out;
720723 } else {
721724 return {};
@@ -733,11 +736,26 @@ bool FileSystem::isFileLocked(const QString &fileName, LockMode mode)
733736{
734737#ifdef Q_OS_WIN
735738 const auto handle = lockFile (fileName, mode);
736- if (!handle) {
739+ if (handle) {
740+ // Lock acquired -> release it immediately
741+ // just closing a file handle does not immediately release the lock leading to system instability
742+
743+ LARGE_INTEGER start;
744+ start.QuadPart = 0 ;
745+ LARGE_INTEGER end;
746+ end.QuadPart = -1 ;
747+ if (!UnlockFile (handle, start.LowPart , start.HighPart , end.LowPart , end.HighPart )) {
748+ const auto error = GetLastError ();
749+ qCWarning (lcFileSystem ()) << " unlock file" << fileName << mode;
750+ qCWarning (lcFileSystem ()) << Q_FUNC_INFO << Utility::formatWinError (error) << fileName;
751+ }
752+ } else {
737753 const auto error = GetLastError ();
754+
738755 if (error == ERROR_SHARING_VIOLATION || error == ERROR_LOCK_VIOLATION ) {
739756 return true ;
740- } else if (error != ERROR_FILE_NOT_FOUND && error != ERROR_PATH_NOT_FOUND ) {
757+ } else {
758+ qCWarning (lcFileSystem ()) << " lock file" << fileName << mode;
741759 qCWarning (lcFileSystem ()) << Q_FUNC_INFO << Utility::formatWinError (error) << fileName;
742760 }
743761 }
0 commit comments