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

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

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

使用匿名管道在父子进程之间通讯:网络

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

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

父进程建立了一个AnonymousPipeServerStream,而后启动子进程,并将建立的AnonymousPipeServerStream的句柄做为参数传递给子进程。以下代码:命令行

//父进程发送消息
Process process = new Process();
process.StartInfo.FileName = @"M:\ABCSolution\Child\Child\bin\Debug\Child.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实例,并今后实例中读取内容,以下代码:code

//子进程读取消息
//使用匿名管道接收内容
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:文本。htm

相关文章
相关标签/搜索