Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>After searching online for a while, I didn't find any good examples.</p> <p>Here are two calls to CreateFile with the intent of locking the file for the life of a process... I use this along side the <a href="http://support.microsoft.com/kb/243953" rel="nofollow">CLimitSingleInstance</a> that uses CreateMutex for a global named mutex.</p> <p>The first call to CreateFile attempts to open it, the second one creates it if necessary. I have a little bit more thorough implementation. I implemented it in Qt, hence the qCritical() instead of std::cout and the QDir::tempPath() instead of getting that some other way.</p> <pre><code>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 &amp;&amp; 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 &amp;&amp; m_hFile != INVALID_HANDLE_VALUE) { return true; } else if(dwLastError == ERROR_SHARING_VIOLATION) { qCritical() &lt;&lt; "Sharing Violation on My.exe.lock"; } else { qCritical() &lt;&lt; "Error reading" &lt;&lt; "My.exe.lock" &lt;&lt; "-" &lt;&lt; dwLastError; } } else if(dwLastError == ERROR_SHARING_VIOLATION) { qCritical() &lt;&lt; "Sharing Violation on My.exe.lock"; } else { qCritical() &lt;&lt; "Unable to obtain file lock -" &lt;&lt; dwLastError; } return false; } } ~SingleInstance() { if ( m_hFile != NULL &amp;&amp; m_hFile != INVALID_HANDLE_VALUE) { ::CloseHandle(m_hFile); //Do as late as possible. m_hFile = NULL; } } } </code></pre> <p>Here is what you would have at the top of your main function:</p> <pre><code>SingleInstance g_SingleInstanceObj(globalId_QA); // Makes sure that the program doesn't run if there is another // instance already running if (g_SingleInstanceObj.IsAnotherInstanceRunning()) { return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload