I'm trying to start a child process in .NET and redirect its output to a named pipe. Attempts to write to stdout in the child process should block until a client actually reads from the named pipe.

Here is my code:

```
using System;
using System.Diagnostics;
using System.IO.Pipes;

namespace psub
{
    class Program
    {
        static void Main(string[] args)
        {
            var pipeName = "testpipe"; // Guid.NewGuid().ToString();
            Console.WriteLine($@"\\.\pipe\{pipeName}");

            var psi = new ProcessStartInfo()
            {
                FileName = "ping",
                Arguments = "google.com",

                UseShellExecute = false,
                RedirectStandardOutput = true
            };

            using (var pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.Out))
            using (var process = new Process { StartInfo = psi })
            {
                pipeServer.WaitForConnection();
                process.Start();
                process.StandardOutput.BaseStream.CopyTo(pipeServer);
                process.WaitForExit();
            }
        }
    }
}

```

When I start this executable, it blocks at `pipeServer.WaitForConnection();`, as expected. I then open a `cmd.exe` and run `type \\.\pipe\testpipe`, to attempt to read from the named pipe [1].

This results in the following error (in the cmd session):

```
All pipe instances are busy.

```

Moreover, in the C# program, `pipeServer.WaitForConnection` finishes, and execution proceeds to `...CopyTo(pipeServer)`, which explodes with:

```
Unhandled Exception: System.IO.IOException: Pipe is broken.

```

I don't understand why the `All pipe instances are busy.` error is happening.

From my understanding there is a single server (instantiated in the C# program) that will write to the named pipe. Data will be ferried to the named pipe server on the program's single, blocked thread as soon as execution reaches `CopyTo`.

There is also a single named pipe client (the `type \\.\pipe\testpipe` process), which will relieve the named pipe of the data the server is trying to write.

So why then does the "All pipe instances are busy" error occur?

I've experimented unsuccessfully with adjusting `new NamedPipeServerStream(pipeName, PipeDirection.Out)` to `new NamedPipeServerStream(pipeName, PipeDirection.Out, 2)`, among other tweaks, but without any real understanding of what the problem is or how this would fix it. Could someone please explain it like I'm five?

---

[1]: The goal is to emulate the [process substitution](https://en.wikipedia.org/wiki/Process_substitution) feature available in UNIX shells, so it is essential that I be able to read from `\\.\pipe\<some file name>`, rather than using C++ or .NET to instantiate a client for the pipe.