How to be notified if someone tries to create a mutex which you already use?

  c++, mutex, winapi, windows

Given my set of 2 different applications, named App1.exe and App2.exe

When both try to create a mutex with the same name, as explained below:

  • On App1.exe, which starts before App2.exe
int main()
{
    std::wstring m = L"LocalMyMutexName";
    HANDLE hMutex = CreateMutexEx(NULL, m.c_str(), CREATE_MUTEX_INITIAL_OWNER, SYNCHRONIZE);
    if (GetLastError() == ERROR_ALREADY_EXISTS)
    {
        std::wcerr << "mutex exists" << std::endl;
        return 1;
    }

    _getch();
    return 0;
}
  • On App2.exe, which starts after App1.exe, I do basically the same:
int main()
{
    std::wstring m = L"LocalMyMutexName";
    HANDLE hMutex = CreateMutexEx(NULL, m.c_str(), CREATE_MUTEX_INITIAL_OWNER, SYNCHRONIZE);
    if (GetLastError() == ERROR_ALREADY_EXISTS)
    {
        std::wcerr << "mutex exists" << std::endl;
        return 1;
    }

    _getch();
    return 0;
}

Then I’m wondering if there is a way for App1.exe, which was started before App2.exe, to be notified or receive an event that App2.exe, which started after App1.exe, tried to create a mutex with the same name.

Source: Windows Questions

LEAVE A COMMENT