如果父进程在子进程启动后创建匿名管道……

那么这些管道句柄将不会由子进程继承。分别建立两个控制台应用程序PipeServerPipeClient,测试代码片段如下

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

请按任意键继续. . .

所以,如果要在子进程运行起来之后再建立管道,还是考虑命名的吧。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

ERROR: si-captcha.php plugin: GD image support not detected in PHP!

Contact your web host and ask them to enable GD image support for PHP.

ERROR: si-captcha.php plugin: imagepng function not detected in PHP!

Contact your web host and ask them to enable imagepng for PHP.

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

Content is available under CC BY-SA 3.0 unless otherwise noted.