Search code examples
c++windowspipehandlesanonymous-pipes

Anonymous Pipes


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 STARTUPINFO 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!


Solution

  • 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.