如何比较两个 HANDLE 类型的变量
我有一个 HANDLE 类型的变量。 第一个 HANDLE 变量是一个没有 PROCESS_QUERY_INFORMATION 访问权限的进程 HANDLE(名称为 hProcess)。 第二个变量也是一个进程句柄(名称为 hwndProcess),我已通过 OpenProcess 函数打开该进程句柄,并具有 PROCESS_QUERY_INFORMATION 访问权限。我确信两个进程应该具有相同的句柄。 但是当我如下比较它们时,它返回 false; if (hProcess==hwndProcess) {做某事} 我该怎么做呢?
I have a variable of HANDLE type.
First HANDLE variable is a process HANDLE (with name hProcess) that does not have PROCESS_QUERY_INFORMATION access right.
Second variable is a process HANDLE (with name hwndProcess) too that I have opened via OpenProcess function and have PROCESS_QUERY_INFORMATION access right. I am sure both processes should have same handle.
But when i compare them as below, it returns false;
if (hProcess==hwndProcess) {do something}
How shall I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有明确的方法来检查两个句柄是否引用同一进程。唯一的方法是查询进程信息并进行检查,例如在每个句柄上使用
GetProcessId
来检查进程ID。如果您没有必要的访问权限来调用所需的查询函数,那么您可以尝试调用
DuplicateHandle
来获取具有更多访问权限的新句柄。但是,如果失败,那么您将无法判断句柄是否属于同一进程。There is not an explicit way to check whether two handles refer to the same process. The only way would be to query the process information and check that, e.g. using
GetProcessId
on each handle to check the process IDs.If you don't have the necessary access rights to call the desired query functions then you can try calling
DuplicateHandle
to get a new handle with more access rights. However, if this fails then you have no way of telling whether the handles are to the same process or not.hProcess 不得持有将要关闭的 Process 的 ProcessHandle。大多数时候它可以并且将会是 NULL。我正在做类似的事情来获取已终止进程的 PID。
if((hProcess == NULL) || (hProcess == GetCurrentProcess())){
pid = GetCurrentProcessId();
} 否则{
pid = ProcessHandleToId(hProcess);
}
您确定这是访问权限问题并且您的函数不会因为句柄为 NULL 而失败吗?
hProcess must not hold the ProcessHandle of the Process that will be closed. It can and will most times be NULL. I'm doing something similar to get the PIDs of terminated processes.
if((hProcess == NULL) || (hProcess == GetCurrentProcess())){
pid = GetCurrentProcessId();
} else {
pid = ProcessHandleToId(hProcess);
}
Are your sure, that it's an access rights problem and your function doesn't fail, because the handle is NULL?
Windows 10 SDK 具有 CompareObjectHandles(HANDLE, HANDLE),如果句柄引用相同的底层内核对象,则返回 TRUE。
而且您不必担心访问权限。
The Windows 10 SDK has CompareObjectHandles(HANDLE, HANDLE) which returns TRUE if the handles refer to the same underlying kernel object.
And you don't have to worry about access rights.