使用匿名管道在進程間通訊 (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

相關文章
相關標籤/搜索