c++ - 仅运行双实例
问题描述
我在寻求帮助。我只需要能够运行我的应用程序的 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);
解决方案
问题是您正在释放信号量,因此在您成功等待它之后立即增加它的计数器,这会减少它的计数器。因此,它的计数器在每个新实例开始时始终为 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;
}
推荐阅读
- c++ - 在 C++ 中计算经过的时间
- amazon-web-services - 如何获取查看 AWS cloudfront 中托管网站的 IP 列表?
- xml - XPath:将兄弟的孩子的属性分配给另一个节点
- ionic3 - 是否可以将 Firebase ML 套件 API 与 ionic 一起使用?
- c - 双向链表中的插入和删除
- php - Wordpress PHP - 在变量中添加 the_permalink 然后回显
- javascript - Angularjs切换移动导航菜单未关闭
- php - 通过同一张表中的两列从数据库中选择一列
- javascript - 类型转换显示省略前导 0
- php - 使用向后兼容脚本将旧 php 脚本与新版本接口