c# - 为什么访问匿名管道时会收到 “Invalid pipe handle”?

标签 c# pipe

我尝试在 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“客户端已停止工作”对话框)。服务器显示:

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

我做错了什么?

最佳答案

找到了。而不是:

new AnonymousPipeServerStream(PipeDirection.In)

应该是:

new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable)

关于c# - 为什么访问匿名管道时会收到 “Invalid pipe handle”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21425311/

相关文章:

awk - 将系统命令的输出分配给变量

vim - 使用 --remote 时如何向 gvim 发送命令?

c++ - 使用 ShellExecute 的进程之间的 IPC

c++ - 如何将消息发送到缓冲区并用前三个单词反向打印消息?

javascript - C# - Zoom GeckoWebBrowser (GeckoFX 45) 就像在 Mozilla Firefox 中一样

c# - WebBrowser 控件与 Windows 窗体之间的交互

c# - 从文本文件加载数据然后将其存储到数据库的最快方法

c# - 为什么当我想注册第二个用户时 MVC 简单成员(member) token 返回 null?

c# - 进程终止。在 Asp.Net Core 3 中找不到系统上安装的有效 ICU 包 - ubuntu

c - 通过管道发送结构而不丢失数据