使用匿名管道在进程间通信 (System.IO.Pipes使用)(转)

原文地址:http://www.cnblogs.com/yukaizhao/archive/2011/08/04/system-io-pipes.html

管道的用途是在同一台机器上的进程之间通信,也可以在同一网络不同机器间通信。在.Net中可以使用匿名管道和命名管道。管道相关的类在System.IO.Pipes命名空间中。.Net中管道的本质是对windows API中管道相关函数的封装。

使用匿名管道在父子进程之间通信:

匿名管道是一种半双工通信,所谓的半双工通信是指通信的两端只有一端可写另一端可读;匿名管道只能在同一台机器上使用,不能在不同机器上跨网络使用。

匿名管道顾名思义就是没有命名的管道,它常用于父子进程之间的通信,父进程在创建子进程是要将匿名管道的句柄作为字符串传递给子进程,看下例子:

父进程创建了一个AnonymousPipeServerStream,然后启动子进程,并将创建的AnonymousPipeServerStream的句柄作为参数传递给子进程。如下代码:

//父进程发送消息
Process process = new Process();
process.StartInfo.FileName = @"M:ABCSolutionChildChildinDebugChild.exe";
//创建匿名管道实例
using (AnonymousPipeServerStream stream =
    new AnonymousPipeServerStream(PipeDirection.Out, System.IO.HandleInheritability.Inheritable))
{
    //将句柄传递给子进程
    process.StartInfo.Arguments = stream.GetClientHandleAsString();
    process.StartInfo.UseShellExecute = false;
    process.Start();

    //销毁子进程的客户端句柄
    stream.DisposeLocalCopyOfClientHandle();
    //向匿名管道中写入内容
    using (StreamWriter sw = new StreamWriter(stream))
    {
        sw.AutoFlush = true;
        sw.WriteLine(Console.ReadLine());
    }
}
process.WaitForExit();
process.Close();

子进程声明了一个AnonymousPipeClientStream实例,并从此实例中读取内容,如下代码:

//子进程读取消息
//使用匿名管道接收内容
using (StreamReader sr = new StreamReader(new AnonymousPipeClientStream(PipeDirection.In, args[0])))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        Console.WriteLine("Echo:{0}", line);
    }
}

这个程序要在cmd命令行中执行,否则看不到执行效果,执行的结果是在父进程中输入一行文本,子进程输出Echo:文本。

原文地址:https://www.cnblogs.com/tianma3798/p/5069338.html