开发者

Anonymous Pipes

开发者 https://www.devze.com 2023-01-12 01:19 出处:网络
I\'ve written a two short programs that use anonymous pipes to communicate.The parent process shares the pipe handles by setting the standard IO handles for the child:

I've written a two short programs that use anonymous pipes to communicate. The parent process shares the pipe handles by setting the standard IO handles for the child:

// -- Set STARTUPI开发者_开发技巧NFO for the spawned process -------------------------
ZeroMemory(&m_ChildSI, sizeof(STARTUPINFO));
GetStartupInfo(&m_ChildSI);

m_ChildSI.dwFlags       = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
m_ChildSI.wShowWindow   = SW_HIDE;
m_ChildSI.hStdError     = m_pipeChild.WritePipeHandle();
m_ChildSI.hStdOutput    = m_pipeChild.WritePipeHandle();
m_ChildSI.hStdInput     = m_pipeParent.ReadPipeHandle();

The child acquires a read pipe handle with a call to GetStdHandle:

hReadPipe = GetStdHandle(STD_INPUT_HANDLE)

My question is: The pipe handles are created by the parent process that calls CloseHandle() on them, once parent and child have finished communication.

Does the child also have to call CloseHandle() also? I was thinking that because these are the standard IO handles, that they'd be automatically deallocated when the process folds.

thanks!


On Win32, kernel objects such as pipes are references by one or more user mode handles. When all handles are closed, the underlying object can be closed.

The handles in each process, while they might have the same value, and might refer to the same object, are different handles, and should be closed separately.


I just read in the document Pipe Handle Inheritance on MSDN that:

"When the child has finished with the pipe, it should close the pipe handle by calling CloseHandle or by terminating, which automatically closes the handle."


Any handle can be left unclosed when application terminates, Windows will free resources automatically. But it is better practice to close them manually so everything is logical and coherent. Leaving handles opened can lead to bugs and leaks when the code is reused or modernized.

0

精彩评论

暂无评论...
验证码 换一张
取 消