<Solved>Cannot create System Wide Mutex within Qt application



  • I need to create a System Wide Mutex in Qt.

    However, Qt, by itself, has QMutex, which is a thread level mutex. There's also something called QSystemMutex, but which is an extended solution and not properly documented, so I didn't want to risk it.

    I then created Windows Mutex...but it seems they're not working system wide. It doesn't stop another instance of the application from starting up.

    Where am I going wrong with this?

    @
    HANDLE ghMutex;
    if ( version == "GSA")
    {
    num_version = 1;
    // G1->GSAParseFile();
    QString temp = "GSAMutex";
    //QByteArray text = QByteArray::fromHex(ghMutex);
    LPCTSTR GSAMutex = (LPCTSTR)temp.data();
    ghMutex = CreateMutex(NULL, FALSE, GSAMutex);
    if (ghMutex == NULL)
    {
    Logger::WriteLog("Multiple instances of type GSA - Sent message, shutting down." );

    QApplication::exit();
    

    }
    else
    {
    sharedMem = new QSharedMemory("GSASharedMemory");
    QString temp1 = "creating mutex with:";
    temp1.append(temp);
    Logger::WriteLog(temp);
    }
    @

    This code doesn't work as intended. Multiple mutex of the same name are apparently created....
    Is the check condition,
    @
    if (ghMutex== NULL)
    @

    sufficient?
    This was how it was noted in MSDN examples.

    Kindly advise.



  • Just do CreateMutex(NULL, FALSE, NULL); You don't need to pass a name (optional parameter).

    However, you could also try to use QSystemSemaphore, which is documented quite well (not QSystemMutex).



  • Got the solution.

    If another one tried createMutex(), it would not return NULL, rather it would open the Mutex.

    One needs to get the Last Error Code and use that as a checking condition.

    @
    LPCTSTR GSAMutex = (LPCTSTR)temp.data();
    ghMutex = CreateMutex(NULL, FALSE, GSAMutex);
    m_dwLastError = GetLastError();

    if (ERROR_ALREADY_EXISTS == m_dwLastError)
    {
    Logger::WriteLog("Multiple instances of type GSA - Sent message, shutting down." );

    a->exit();
    

    }
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.