Close handle to a mutex in another process

╄→гoц情女王★ 提交于 2020-01-03 03:15:07

问题


I want to close a handle to a mutex located in another process, so I can run more than one instance of the application.

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.

The mutex that I need to close is \Sessions\1\BaseNamedObjects\Oberon_Minesweeper_Singleton, which I found using Process Explorer.

After closing this mutex I was able to launch two games of Minesweeper, but I want to do this in my program using C++.

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;
}

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.


回答1:


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.



来源:https://stackoverflow.com/questions/8690969/close-handle-to-a-mutex-in-another-process

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!