14.2.1 Using Anonymous Pipes

A typical use of anonymous pipes is for redirecting the standard input or output of a child process. To use a pipe for redirecting the standard output of a child process, the parent process would first use DuplicateHandle to save a copy of its standard output handle. Then it would create the pipe and use SetStdHandle to set its standard output to the write handle of the pipe. After the child process has been created (CreateProcess), the parent uses SetStdHandle again to restore its original standard output. The child process can use GetStdHandle to retrieve a handle to the pipe. The procedure is similar for redirecting standard input, except that the pipe's read handle is used for the child's standard input, and the parent must ensure that the child does not inherit the pipe's write handle.

Typically, the read and write handles to the pipe are created as inheritable handles (by specifying a SECURITY_ATTRIBUTES parameter with its bInheritHandle flag set to TRUE in the CreatePipe call). In some situations, however, you will want to prevent one of the handles from being inherited. For example, consider the case of a pipe whose read handle has been redirected to be standard input for a child process. The child process will read from its standard input (the pipe) until it reads end-of-file which occurs only when all write handles to the pipe are closed. If the child has inherited the pipe's write handle, it will be blocked while reading from the pipe because of its own open write handle. The solution to this problem is to make the write handle not inheritable. This is done by using DuplicateHandle to create a non-inheritable duplicate of the handle, and then using CloseHandle to close the inheritable handle. Alternatively, the CreatePipe call could create non- inheritable handles, and then DuplicateHandle could be used to create an inheritable duplicate.

Refer to Chapter 3, “Processes and Threads” for an example program that uses anonymous pipes to redirect I/O.