gpt4 book ai didi

process - DuplicateHandle,为什么要复制而不是仅仅获取?

转载 作者:行者123 更新时间:2023-12-02 13:44:00 24 4
gpt4 key购买 nike

为什么一个进程想要从 Win32API 调用 DuplicateHandle,并从另一个进程获取它,而不是仅仅获取某个对象本身的句柄?

调用 DuplicateHandle 或其他东西有什么好处吗?

最佳答案

您可以在《Microsoft Windows 的应用程序编程》第 6.8 章中找到答案。

Gaining a Sense of One's Own Identity
Sometimes you might need to acquire a real handle to a thread instead of a pseudo-handle. By "real," I mean a handle that unambiguously identifies a unique thread. Examine the following code:
DWORD WINAPI ParentThread(PVOID pvParam) {
HANDLE hThreadParent = GetCurrentThread();
CreateThread(NULL, 0, ChildThread, (PVOID) hThreadParent, 0, NULL);
// Function continues...
}

DWORD WINAPI ChildThread(PVOID pvParam) {
HANDLE hThreadParent = (HANDLE) pvParam;
FILETIME ftCreationTime, ftExitTime, ftKernelTime, ftUserTime;
GetThreadTimes(hThreadParent,
&ftCreationTime, &ftExitTime, &ftKernelTime, &ftUserTime);
// Function continues...
}
Can you see the problem with this code fragment? The idea is to have the parent thread pass to the child thread a thread handle that identifies the parent thread. However, the parent thread passes a pseudo-handle, not a real handle. When the child thread begins executing, it passes the pseudo-handle to the GetThreadTimes function, which causes the child thread to get its own CPU times, not the parent thread's CPU times. This happens because a thread pseudo-handle is a handle to the current thread— that is, a handle to whichever thread is making the function call.

To fix this code, we must turn the pseudo-handle into a real handle. The DuplicateHandle function (discussed in Chapter 3) can do this transformation

关于process - DuplicateHandle,为什么要复制而不是仅仅获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2172079/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com