14.1.1 Anonymous Pipes

An anonymous pipe is used to transfer information between related processes. One process creates the pipe, and then the read and write handles to the pipe can be inherited by its child processes. The pipe can then be used for communication between a parent and child process, or between two children of the same process. This type of pipe is typically used to redirect the standard input or standard output of a child process.

The CreatePipe function creates a new anonymous pipe and returns handles to the read and write ends of the pipe. The handles can be inherited by child processes if the function call specified a SECURITY_ATTRIBUTES parameter with its bInheritHandle flag set to TRUE. DuplicateHandle can be used to create a non-inheritable duplicate of an inheritable pipe handle, or to create an inheritable duplicate of a non-inheritable pipe handle. CloseHandle is used to close a pipe handle.

CreatePipe allows the creating process to suggest a buffer size for the pipe, or you can use the default size. Anonymous pipes are always local, and cannot be used for communication over a network.

The read handle to the pipe has only read access to the pipe, and the write handle has only write access to the pipe. To read from the pipe, a process uses the read handle in a call to ReadFile. The ReadFile call will block until the specified number of bytes have been read, or until all handles to the write end of the pipe have been closed. To write to the pipe, a process uses the write handle in a call to WriteFile. If the pipe's buffer is full, a call to WriteFile will block until some other process reads from the pipe to make more buffer space available. ReadFileEx and WriteFileEx cannot be used with anonymous pipes, and when using ReadFile or WriteFile with an anonymous pipe, the function's lpOverLapped parameter is ignored.

An anonymous pipe exists until all handles to both read and write ends of the pipe have been closed. The order in which the handles are closed is important in some situations. For example, if the read handle is closed before the write handle is closed, writing to the pipe generates an error.