那么这些管道句柄将不会由子进程继承。分别建立两个控制台应用程序PipeServer
和PipeClient
,测试代码片段如下
static class Program { static void Main(string[] args) { var pipe1 = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable); var pipe2 = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable); using (var proc = Process.Start(new ProcessStartInfo("dotnet", $"\"{typeof(ClientProgram).Assembly.Location}\"") { RedirectStandardInput = true, RedirectStandardOutput = true })) { proc.StandardInput.WriteLine(pipe1.GetClientHandleAsString()); WriteString(pipe1, "Pipe1"); pipe1.Close(); Console.WriteLine(proc.StandardOutput.ReadLine()); proc.StandardInput.WriteLine(pipe2.GetClientHandleAsString()); WriteString(pipe2, "Pipe2"); pipe2.Close(); Console.WriteLine(proc.StandardOutput.ReadLine()); var pipe3 = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable); proc.StandardInput.WriteLine(pipe3.GetClientHandleAsString()); WriteString(pipe3, "Pipe3"); pipe3.Close(); Console.WriteLine(proc.StandardOutput.ReadLine()); } } private static void WriteString(Stream s, string content) { var buffer = Encoding.ASCII.GetBytes(content); s.Write(buffer, 0, buffer.Length); s.Flush(); } }
public static class ClientProgram { static void Main(string[] args) { while (true) { var handle = Console.ReadLine(); using (var pipe = new AnonymousPipeClientStream(PipeDirection.In, handle)) using (var reader = new StreamReader(pipe, Encoding.ASCII)) { var content = reader.ReadLine(); Console.WriteLine(content); } } } }
使用 VS 2017 + .NET Core 2.0 运行测试,结果如下
Pipe1 Pipe2 Unhandled Exception: System.IO.IOException: Invalid pipe handle. at System.IO.Pipes.PipeStream.ValidateHandleIsPipe(SafePipeHandle safePipeHandle) at System.IO.Pipes.AnonymousPipeClientStream.Init(PipeDirection direction, SafePipeHandle safePipeHandle) at System.IO.Pipes.AnonymousPipeClientStream..ctor(PipeDirection direction, String pipeHandleAsString) at PipeClient.ClientProgram.Main(String[] args) in \PipeTest\PipeClient\Program.cs:line 16 请按任意键继续. . .
所以,如果要在子进程运行起来之后再建立管道,还是考虑命名的吧。