那么这些管道句柄将不会由子进程继承。分别建立两个控制台应用程序PipeServer和PipeClient,测试代码片段如下
|
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
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(); } } |
|
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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 运行测试,结果如下
|
1 2 3 4 5 6 7 8 9 10 |
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 请按任意键继续. . . |
所以,如果要在子进程运行起来之后再建立管道,还是考虑命名的吧。
