HOW TO:使用匿名管道在本機處理序之間進行通訊

更新:2007 年 11 月

匿名管道提供的功能比具名管道少,但其負荷也少。您可以使用匿名管道,讓本機電腦上的處理序之間更容易通訊。匿名管道不能用於網路上的通訊。

範例

下列範例示範如何使用匿名管道,將字串從父處理序 (Parent Process) 傳送到子處理序 (Child Process)。這個範例會在父處理序中建立一個 AnonymousPipeServerStream 物件,並將其 PipeDirection 值設為 Out。父處理序接著再建立一個子處理序,方式是使用用戶端控制碼建立 AnonymousPipeClientStream 物件。這個子處理序的 PipeDirection 值為 In

父處理序接著將使用者提供的字串傳送到子處理序。主控台會顯示子處理序中的這個字串。

下列範例顯示伺服器處理序。

Imports System
Imports System.IO
Imports System.IO.Pipes
Imports System.Diagnostics

Class PipeServer
    Shared Sub Main()
        Dim pipeClient As New Process()
        pipeClient.StartInfo.FileName = "pipeClient.exe"

        Using pipeServer As New AnonymousPipeServerStream( _
                PipeDirection.Out, HandleInheritability.Inheritable)

            Console.WriteLine("Current TransmissionMode: {0}.", _
                              pipeServer.TransmissionMode)

            'Anonymous pipes do not support Message mode.
            Try
                Console.WriteLine("Setting ReadMode to 'Message'.")
                pipeServer.ReadMode = PipeTransmissionMode.Message
            Catch e As Exception
                Console.WriteLine("EXCEPTION: {0}", e.Message)
            End Try

            ' Pass the client process a handle to the server
            pipeClient.StartInfo.Arguments = _
                pipeServer.GetClientHandleAsString()
            pipeClient.StartInfo.UseShellExecute = False
            pipeClient.Start()

            pipeServer.DisposeLocalCopyOfClientHandle()

            Try
                'Read user input and send that to the client process.
                Using sw As New StreamWriter(pipeServer)
                    sw.AutoFlush = True
                    Console.Write("Enter text: ")
                    sw.WriteLine(Console.ReadLine())
                End Using
            Catch e As Exception
                Console.WriteLine("ERROR: {0}", e.Message)
            End Try

            pipeClient.WaitForExit()
            pipeClient.Close()
        End Using
    End Sub
End Class
using System;
using System.IO;
using System.IO.Pipes;
using System.Diagnostics;

class PipeServer
{
    static void Main()
    {
        Process pipeClient = new Process();
        pipeClient.StartInfo.FileName = "pipeClient.exe";

        using (AnonymousPipeServerStream pipeServer =
            new AnonymousPipeServerStream(PipeDirection.Out,
            HandleInheritability.Inheritable))
        {
            Console.WriteLine("Current TransmissionMode: {0}.",
                pipeServer.TransmissionMode);

            // Anonymous pipes do not support Message mode.
            try
            {
                Console.WriteLine("Setting ReadMode to \"Message\".");
                pipeServer.ReadMode = PipeTransmissionMode.Message;
            }
            catch (NotSupportedException e)
            {
                Console.WriteLine("EXCEPTION: {0}", e.Message);
            }

            // Pass the client process a handle to the server.
            pipeClient.StartInfo.Arguments =
                pipeServer.GetClientHandleAsString();
            pipeClient.StartInfo.UseShellExecute = false;
            pipeClient.Start();

            pipeServer.DisposeLocalCopyOfClientHandle();

            try
            {
                // Read user input and send that to the client process.
                using (StreamWriter sw = new StreamWriter(pipeServer))
                {
                    sw.AutoFlush = true;
                    Console.Write("Enter text: ");
                    sw.WriteLine(Console.ReadLine());
                }
            }
            // Catch the IOException that is raised if the pipe is broken
            // or disconnected.
            catch (IOException e)
            {
                Console.WriteLine("ERROR: {0}", e.Message);
            }
        }

        pipeClient.WaitForExit();
        pipeClient.Close();
    }
}

下列範例顯示用戶端處理序。伺服器處理序會啟動用戶端處理序,給予該處理序用戶端控制碼。從用戶端程式碼產生的可執行檔應名為 pipeClient.exe 並在執行伺服器處理序前,複製到與伺服器可執行檔相同的目錄中。

Imports System
Imports System.IO
Imports System.IO.Pipes

Class PipeClient

    Shared Sub Main(ByVal args As String())
        If (args.Length > 0) Then

            Using pipeClient As New AnonymousPipeClientStream( _
                PipeDirection.In, args(0))

                Console.WriteLine("Current TransmissionMode: {0}.", _
                   pipeClient.TransmissionMode)

                ' Anonymous Pipes do not support Message mode.
                Try
                    Console.WriteLine("Setting ReadMode to 'Message'.")
                    pipeClient.ReadMode = PipeTransmissionMode.Message
                Catch e As NotSupportedException
                    Console.WriteLine("EXCEPTION: {0}", e.Message)
                End Try

                Using sr As New StreamReader(pipeClient)

                    ' Display the read text to the console
                    Dim temp As String
                    temp = sr.ReadLine()
                    While Not temp = Nothing
                        Console.WriteLine(temp)
                        temp = sr.ReadLine()
                    End While
                End Using
            End Using
        End If
        Console.Write("Press Enter to continue...")
        Console.ReadLine()
    End Sub
End Class
using System;
using System.IO;
using System.IO.Pipes;

class PipeClient
{
    static void Main(string[] args)
    {
        if (args.Length > 0)
        {
            using (PipeStream pipeClient =
                new AnonymousPipeClientStream(PipeDirection.In, args[0]))
            {

                Console.WriteLine("Current TransmissionMode: {0}.",
                   pipeClient.TransmissionMode);

                // Anonymous Pipes do not support Message mode.
                try
                {
                    Console.WriteLine("Setting ReadMode to \"Message\".");
                    pipeClient.ReadMode = PipeTransmissionMode.Message;
                }
                catch (NotSupportedException e)
                {
                    Console.WriteLine("EXCEPTION: {0}", e.Message);
                }

                using (StreamReader sr = new StreamReader(pipeClient))
                {
                    // Display the read text to the console
                    string temp;
                    while ((temp = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(temp);
                    }
                }
            }
        }
        Console.Write("Press Enter to continue...");
        Console.ReadLine();
    }
}

請參閱

工作

HOW TO:使用具名管道透過網路在處理序之間進行通訊

概念

管道