我尝试在 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/