3

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!

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
  • 1
    I thought you always had to close both sides of a pipe, at least to get rid of the entry in the file descriptor table... – James Aug 19 '10 at 13:11
  • I would normally check in Visual Studio / debug mode for leaked memory or handles by using Application Verifier - but because the child process is created by the parent, the child doesn't run through Visual Studio, so I was a little uncertain. I 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." So I guess we're both right! –  Aug 19 '10 at 13:19
  • You can always attach debugger to running process (menu `Debug->Attach to process` or something like that). – adf88 Aug 19 '10 at 14:21

3 Answers3

3

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.

Chris Becke
  • 34,244
  • 12
  • 79
  • 148
1

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

0

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.

adf88
  • 4,277
  • 1
  • 23
  • 21