Do I have to close inherited handle later owned by child process?
Asked Answered
S

1

12

Microsoft played safe here. In their article, "Creating a Child Process with Redirected Input and Output", they are saying:

The remaining open handles are cleaned up when this process terminates.
To avoid resource leaks in a larger application, close handles explicitly.

Which is perfectly useless. What handles? In which process?


I want to get my head around it.

When a handle is created in parent process with SECURITY_ATTRIBUTES.bInheritHandle = TRUE, a child process can see and use it, and the handle has the same value and access rights in both processes.

But is it the same handle, or is it a copy that happen to have same numerical representation?

If I pass a hRead handle to a child process so that it can read from a pipe, and the child process closes the handle, do I also need to close it from the parent process? Will it not wipe the pipe from under the child process?

My experiments show that CloseHandle returns success when trying to close a hRead handle passed to the child after the child has closed it. This argues strongly for Yes, you should close it. However, I would appreciate a more solid advice here.

Shufu answered 5/7, 2011 at 10:19 Comment(0)
B
14

You hit the nail on the head there. Win32 handles act as user mode references to an underlying kernel mode object. Handles (references) to new and existing objects are typically created via some kind of CreateXXX call - additional references can be created in the current, or other processes, by calling DuplicateHandle - {or marking a handle as inheritable and creating a new process - which duplicates a handle from the current process into the child process - ensuring that the handle value is identical.}

At that point, there are (at least) two references to the kernel object, both of which need to be closed to unlock the object and free any consumed resources.

Butterfat answered 5/7, 2011 at 10:28 Comment(1)
Ah. So the handle is cloned when I spawn a child process. That is what I was after.Shufu

© 2022 - 2024 — McMap. All rights reserved.