After searching the Internet for a while, I did not find any good examples.
Here are two calls to CreateFile to lock the file for the life of the process ... I use this on the CLimitSingleInstance side, which uses CreateMutex for the mutex global name.
The first call to CreateFile tries to open it, and the second, if necessary. I have a slightly more thorough implementation. I implemented it in Qt and then instead of qdir :: tempPath () instead of qdir :: temp () instead of qdir :: temp () instead of getting another way.
class SingleInstance { protected: DWORD m_dwLastError; HANDLE m_hFile; public: SingleInstance(const char *strMutexName) { } bool attemptToLockTempFile() { QString lockFile = QDir::tempPath() + "/My.exe.lock"; m_hFile = CreateFileA(lockFile.toLocal8Bit().data(), GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); DWORD dwLastError = GetLastError(); if(m_hFile != NULL && m_hFile != INVALID_HANDLE_VALUE) { return true; } else { if(dwLastError == ERROR_FILE_NOT_FOUND ) { m_hFile = CreateFileA(lockFile.toLocal8Bit().data(), GENERIC_READ, 0, NULL, CREATE_NEW, 0, NULL); dwLastError = GetLastError(); if(m_hFile != NULL && m_hFile != INVALID_HANDLE_VALUE) { return true; } else if(dwLastError == ERROR_SHARING_VIOLATION) { qCritical() << "Sharing Violation on My.exe.lock"; } else { qCritical() << "Error reading" << "My.exe.lock" << "-" << dwLastError; } } else if(dwLastError == ERROR_SHARING_VIOLATION) { qCritical() << "Sharing Violation on My.exe.lock"; } else { qCritical() << "Unable to obtain file lock -" << dwLastError; } return false; } } ~SingleInstance() { if ( m_hFile != NULL && m_hFile != INVALID_HANDLE_VALUE) { ::CloseHandle(m_hFile);
Here is what you would have at the top of your main function:
SingleInstance g_SingleInstanceObj(globalId_QA);
source share