【问题标题】:Why do I receive “Invalid pipe handle” when accessing an anonymous pipe?为什么在访问匿名管道时收到“无效的管道句柄”?
【发布时间】:2014-01-29 08:03:33
【问题描述】:

我尝试在 C# 中使用匿名管道,但即使是最基本的示例也失败了。这是服务器控制台应用程序:

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);
        }
    }
}

这里是控制台客户端应用程序的源代码:

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);
            }
        }
    }
}

当我启动服务器时,客户端应用程序崩溃(Windows“客户端已停止工作”对话框)。服务器显示:

客户端发送了以下字节:-1

未处理的异常:System.IO.IOException:无效的管道句柄。
在 […]
在 C:\[...]\Client\Program.cs:line 9 中的 Client.program.Main(String[] args) 处

我做错了什么?

【问题讨论】:

    标签: c# pipe


    【解决方案1】:

    找到了。而不是:

    new AnonymousPipeServerStream(PipeDirection.In)
    

    应该是:

    new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable)
    

    【讨论】:

      猜你喜欢
      • 2023-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      相关资源
      最近更新 更多