我尝试在 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
Unhanded 异常:System.IO.IOException:无效的管道句柄。
在[…]
在 C:\[…]\Client\Program.cs 中的 Client.program.Main(String[] args) 处:第 9 行
我做错了什么?
找到了。而不是:
new AnonymousPipeServerStream(PipeDirection.In)
应该是:
new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable)
我已经因为这个错误而自杀了好几天了。我终于发现从 shell 运行该进程,即。
pipeProcess.StartInfo.UseShellExecute = true;
导致此错误。 我不知道,它可能写在某个地方,匿名管道不是从 shell 传播的。
另外,我可以推荐 https://processhacker.sourceforge.io/ 进行调试。