问题描述
我想关闭位于另一个进程中的互斥锁的句柄,因此我可以运行该应用程序的多个实例.
I want to close a handle to a mutex located in another process, so I can run more than one instance of the application.
我已经知道可以做到,请参阅Process Explorer .示例:Windows Minesweeper (Windows 7)使用互斥锁仅允许一个游戏,所以我想以它为例,因为它已预先安装在Windows中,因此,你们更容易指导我
I already know this can be done, see Process Explorer. Example: Windows Minesweeper (Windows 7) uses a mutex to only allow one game, so I thought I would use it as an example since it's pre-installed with Windows and therefore easier for you guys to guide me.
我需要关闭的互斥锁是\Sessions\1\BaseNamedObjects\Oberon_Minesweeper_Singleton
,我是使用Process Explorer找到的.
The mutex that I need to close is \Sessions\1\BaseNamedObjects\Oberon_Minesweeper_Singleton
, which I found using Process Explorer.
关闭此互斥锁后,我可以启动两款 Minesweeper 游戏,但是我想在我的程序中使用C ++来实现.
After closing this mutex I was able to launch two games of Minesweeper, but I want to do this in my program using C++.
经过一些搜索,我发现我可能需要 DuplicateHandle .到目前为止,我还无法关闭此互斥锁上的句柄.
After some searching I have found that I might need the API DuplicateHandle. So far I haven't been able to close the handle on this mutex.
到目前为止,这是我的代码:
Here is my code so far:
#include <Windows.h>
#include <iostream>
using namespace std;
void printerror(LPSTR location){
printf("Error: %s_%d", location, GetLastError());
cin.get();
}
int main(){
DWORD pid = 0;
HWND hMineWnd = FindWindow("Minesweeper", "Minesveiper");
GetWindowThreadProcessId(hMineWnd, &pid);
HANDLE hProc =OpenProcess(PROCESS_DUP_HANDLE, 0, pid);
if(hProc == NULL){
printerror("1");
return 1;
}
HANDLE hMutex = OpenMutex(MUTEX_ALL_ACCESS, TRUE, "Oberon_Minesweeper_Singleton");
if(hMutex == NULL){
printerror("2");
return 2;
}
if(DuplicateHandle(hProc, hMutex, NULL, 0, 0, FALSE, DUPLICATE_CLOSE_SOURCE) == 0){
printerror("3");
return 3;
}
if(CloseHandle(hMutex) == 0){
printerror("4");
return 4;
}
return 0;
}
此代码返回0,但是互斥锁仍然存在,并且我无法启动更多的Minesweeper游戏.我认为我对DuplicateHandle的某些参数是错误的.
This code returns 0, but the mutex is still there, and I am not able to launch more games of Minesweeper. I think some of my parameters to DuplicateHandle are wrong.
推荐答案
DuplicateHandle
的第二个参数期望在源进程的上下文中有效的开放对象句柄" 我相信您要传递的句柄仅在当前进程中有效(OpenMutex
为现有的互斥对象创建一个新的句柄).您可能需要确定互斥对象的句柄在远程进程中是什么,并在调用DuplicateHandle
时使用该值.
The second argument to DuplicateHandle
expects "an open object handle that is valid in the context of the source process", however I believe the handle you're passing in would only be valid within the current process (OpenMutex
creates a new handle to an existing mutex object). You'll likely need to determine what the mutex's handle is in the remote process, and use that value when calling DuplicateHandle
.
这篇关于在另一个过程中关闭互斥锁的句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!