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 c开发者_Python百科loses 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.
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.
精彩评论