1

我有一些事件句柄,并将它们添加到列表中。我想知道我是否可以存储这些句柄,关闭本地句柄,以后仍然使用存储的句柄。

例子:

std::map<std::string, HANDLE> Events;

DWORD OpenSingleEvent(std::string EventName, bool InheritHandle, DWORD dwDesiredAccess, DWORD dwMilliseconds)
{
    Handle hEvent = OpenEvent(dwDesiredAccess, InheritHandle, EventName.c_str()); //Local Handle.
    if (hEvent)
    {
        DeleteSingleEvent(EventName); //Delete the correct/old handle in the map.
        Events.insert(EventName, hEvent);  //Add this new handle to the map.
        DWORD Result = WaitForSingleObject(hEvent, dwMilliseconds);
        CloseHandle(hEvent);  //Close THIS handle. Not the one in my Map.
        return Result;
    }
    CloseHandle(hEvent);  //Close this handle.
    return WAIT_FAILED;
}

上面的方法有用吗?如果没有,还有其他方法可以做到这一点吗?它用于共享内存通信,所以我不能复制句柄,因为我只有客户端 PID 而不是服务器的。

也有人可以解释 InheritHandle 的作用吗?我使用的函数是 OpenEvent,它具有该参数,但我不确定它的作用。

4

1 回答 1

2

A HANDLE is simply a void *, it's a token which actually represents an object in kernel space. Calling CloseHandle actually deallocates the kernel object so the short answer to your question is no, you can't keep a list of them and then close all the local ones. All you'll have is a list of void* which don't represent anything.

What you can do is use DuplicateHandle which actually creates another kernel object on your behalf. However... why not just close the handles when you've finished with the entry in the list?

于 2012-10-18T15:23:29.480 回答