Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

pipe

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?

like image 234
Arseni Mourzenko Avatar asked Jan 29 '14 08:01

Arseni Mourzenko


Video Answer


1 Answers

Found it. Instead of:

new AnonymousPipeServerStream(PipeDirection.In)

it should be:

new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable)
like image 136
Arseni Mourzenko Avatar answered Sep 28 '22 03:09

Arseni Mourzenko