Why do I receive “Invalid pipe handle” when accessing an anonymous pipe?
Asked Answered
C

2

6

I tried to use anonymous pipes in C#, but it fails even with the most basic example. Here's the server console app:

namespace Server
{
    using System;
    using System.Diagnostics;
    using System.IO.Pipes;

    public static class Program
    {
        public static void Main()
        {
            using (var pipe = new AnonymousPipeServerStream(PipeDirection.In))
            {
                var pipeName = pipe.GetClientHandleAsString();

                var startInfo = new ProcessStartInfo("Client.exe", pipeName);
                startInfo.UseShellExecute = false;
                using (var process = Process.Start(startInfo))
                {
                    pipe.DisposeLocalCopyOfClientHandle();

                    var receivedByte = pipe.ReadByte();
                    Console.WriteLine(
                        "The client sent the following byte: " + receivedByte);

                    process.WaitForExit();
                }
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey(true);
        }
    }
}

And here is the source code of the console client app:

namespace Client
{
    using System.IO.Pipes;

    public static class Program
    {
        public static void Main(string[] args)
        {
            using (var pipe = new AnonymousPipeClientStream(
                PipeDirection.Out, args[0]))
            {
                pipe.WriteByte(0x65);
            }
        }
    }
}

When I launch the server, the client app crashes (with Windows "Client has stopped working" dialog). The server displays:

The client sent the following byte: -1

Unhanded Exception: System.IO.IOException: Invalid pipe handle.
at […]
at Client.program.Main(String[] args) in C:\[…]\Client\Program.cs:line 9

What am I doing wrong?

Christiachristian answered 29/1, 2014 at 8:3 Comment(0)
C
3

Found it. Instead of:

new AnonymousPipeServerStream(PipeDirection.In)

it should be:

new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable)
Christiachristian answered 29/1, 2014 at 9:16 Comment(0)
C
1

I've been killing myself over this error for some days. I finally found that running the process from a shell, ie.

pipeProcess.StartInfo.UseShellExecute = true;

leads to this error. I don't know, it's probably written somewhere that Anonymous Pipes are not propagated from shells.

Also, I can recommend https://processhacker.sourceforge.io/ for debugging this.

Compliance answered 4/4, 2024 at 11:10 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.