6/2/08

What is duplicating handle ?

The parent and child processes may require different access to an object identified by a handle that the child inherits. A process may also need a real, inheritable process handle rather than the pseudo handle produced by GetCurrentProcess for use by a child process. To address this issue, the parent process can create a duplicate handle with the desired access and inheritability.

Function to duplicate handles:

BOOL DuplicateHandle (
HANDLE hSourceProcessHandle,
HANDLE hSourceHandle,
HANDLE hTargetProcessHandle,
LPHANDLE lphTargetHandle,
DWORD dwDesiredAccess,
BOOL bInheritHandle,
DWORD dwOptions)

Upon completion, lphTargetHandle points to a copy of the original handle, hSourceHandle. hSourceHandle is a handle in the process indicated by hSourceProcessHandle and must have PROCESS_DUP_HANDLE access; DuplicateHandle will fail if the source handle does not exist in the source process. The new handle, which is pointed to by lphTargetHandle, is valid in the target process, hTargetProcessHandle. Note that three processes are involved, including the calling process. Frequently, these target and source processes are the calling process, and the handle is obtained from GetCurrentProcess. Also notice that it is possible to create a handle in another process; if you do this, you then need a mechanism for informing the other process of the new handle's identity.

DuplicateHandle can be used for any handle type.

If dwDesiredAccess is not overridden by DUPLICATE_SAME_ACCESS in dwOptions, it has many possible values .

dwOptions is any combination of two flags.

  • DUPLICATE_CLOSE_SOURCE causes the source handle to be closed.

  • DUPLICATE_SAME_ACCESS causes dwDesiredAccess to be ignored.

Reminder: The Windows kernel maintains a reference count for all objects; this count represents the number of distinct handles referring to the object. This count is not available to the application program, however. An object cannot be destroyed until the last handle is closed and the reference count becomes zero. Inherited and duplicate handles are both distinct from the original handles and are represented in the reference count.

On the other hand, a handle passed from one process to another through some form of IPC is not a distinct handle, so if one process closes the handle, the handle cannot be used by any other process.


No comments: