首页 > 解决方案 > 仅运行双实例

问题描述

我在寻求帮助。我只需要能够运行我的应用程序的 2 个实例,但是使用下面的代码仍然可以启动超过 2 个实例。我不确定我错过了什么。

这是代码:

const char szUniqueNamedSemaphore[] = "Amazon.exe";
HANDLE hHandle = CreateSemaphore(NULL, 2, 2, szUniqueNamedSemaphore);
if (!hHandle)
{
    MessageBox(NULL, "Unexpected error creating Execution!", "Amazon.exe", MB_OK);
    return FALSE;
}
if (WaitForSingleObject(hHandle, 0) != WAIT_OBJECT_0)
{
    MessageBox(NULL, "Game is already running 2 times, additional Execution is prohibited!", "Amazon.exe", MB_OK);
    return FALSE;
}
ReleaseSemaphore(hHandle, 1, NULL);

标签: c++winapi

解决方案


问题是您正在释放信号量,因此在您成功等待它之后立即增加它的计数器,这会减少它的计数器。因此,它的计数器在每个新实例开始时始终为 2。在完成工作后准备退出程序之前,不要释放信号量,例如:

const char* szUniqueNamedSemaphore = "Amazon.exe";

int main() // or WinMain()...
{
    HANDLE hHandle = CreateSemaphore(NULL, 2, 2, szUniqueNamedSemaphore);
    if (!hHandle)
    {
        MessageBox(NULL, "Unexpected error creating Execution!", "Amazon.exe", MB_OK);
        return 0;
    }

    DWORD ret = WaitForSingleObject(hHandle, 0);
    if (ret != WAIT_OBJECT_0)
    {
        if (ret == WAIT_TIMEOUT)
            MessageBox(NULL, "Game is already running 2 times, additional Execution is prohibited!", "Amazon.exe", MB_OK);
        else
            MessageBox(NULL, "Unexpected error waiting on Execution!", "Amazon.exe", MB_OK);
        return 0;
    }

    // do your normal work...

    ReleaseSemaphore(hHandle, 1, NULL);
    return 0;
}

推荐阅读