作法:使用匿名管道進行本機處理序間通訊

匿名管道會在本機電腦上提供處理序間通訊。 它們提供的功能比具名管道少,但其負荷也比較小。 您可以使用匿名管道,讓本機電腦上的處理序間通訊更容易。 您無法透過網路,使用匿名管道進行通訊。

若要實作匿名管道,請使用 AnonymousPipeServerStreamAnonymousPipeClientStream 類別。

範例 1

下列範例會示範如何使用匿名管道,將字串從父處理序傳送至子處理序。 此範例會在父處理序中,使用 OutPipeDirection 值建立 AnonymousPipeServerStream 物件。接著,父處理序會使用建立 AnonymousPipeClientStream 物件的用戶端控制代碼來建立子處理序。 子處理序具有 InPipeDirection 值。

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

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

#using <System.dll>
#using <System.Core.dll>

using namespace System;
using namespace System::IO;
using namespace System::IO::Pipes;
using namespace System::Diagnostics;

ref class PipeServer
{
public:
    static void Main()
    {
        Process^ pipeClient = gcnew Process();

        pipeClient->StartInfo->FileName = "pipeClient.exe";

        AnonymousPipeServerStream^ pipeServer =
            gcnew AnonymousPipeServerStream(PipeDirection::Out,
            HandleInheritability::Inheritable);

        Console::WriteLine("[SERVER] Current TransmissionMode: {0}.",
            pipeServer->TransmissionMode);

        // 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.
            StreamWriter^ sw = gcnew StreamWriter(pipeServer);

            sw->AutoFlush = true;
            // Send a 'sync message' and wait for client to receive it.
            sw->WriteLine("SYNC");
            pipeServer->WaitForPipeDrain();
            // Send the console input to the client process.
            Console::Write("[SERVER] Enter text: ");
            sw->WriteLine(Console::ReadLine());
            sw->Close();
        }
        // Catch the IOException that is raised if the pipe is broken
        // or disconnected.
        catch (IOException^ e)
        {
            Console::WriteLine("[SERVER] Error: {0}", e->Message);
        }
        pipeServer->Close();
        pipeClient->WaitForExit();
        pipeClient->Close();
        Console::WriteLine("[SERVER] Client quit. Server terminating.");
    }
};

int main()
{
    PipeServer::Main();
}
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("[SERVER] Current TransmissionMode: {0}.",
                pipeServer.TransmissionMode);

            // 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;
                    // Send a 'sync message' and wait for client to receive it.
                    sw.WriteLine("SYNC");
                    pipeServer.WaitForPipeDrain();
                    // Send the console input to the client process.
                    Console.Write("[SERVER] Enter text: ");
                    sw.WriteLine(Console.ReadLine());
                }
            }
            // Catch the IOException that is raised if the pipe is broken
            // or disconnected.
            catch (IOException e)
            {
                Console.WriteLine("[SERVER] Error: {0}", e.Message);
            }
        }

        pipeClient.WaitForExit();
        pipeClient.Close();
        Console.WriteLine("[SERVER] Client quit. Server terminating.");
    }
}
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("[SERVER] Current TransmissionMode: {0}.",
                pipeServer.TransmissionMode)

            ' 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
                    ' Send a 'sync message' and wait for client to receive it.
                    sw.WriteLine("SYNC")
                    pipeServer.WaitForPipeDrain()
                    ' Send the console input to the client process.
                    Console.Write("[SERVER] Enter text: ")
                    sw.WriteLine(Console.ReadLine())
                End Using
            Catch e As IOException
                ' Catch the IOException that is raised if the pipe is broken
                ' or disconnected.
                Console.WriteLine("[SERVER] Error: {0}", e.Message)
            End Try
        End Using

        pipeClient.WaitForExit()
        pipeClient.Close()
        Console.WriteLine("[SERVER] Client quit. Server terminating.")
    End Sub
End Class

範例 2

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

#using <System.Core.dll>

using namespace System;
using namespace System::IO;
using namespace System::IO::Pipes;

ref class PipeClient
{
public:
    static void Main(array<String^>^ args)
    {
        if (args->Length > 1)
        {
            PipeStream^ pipeClient = gcnew AnonymousPipeClientStream(PipeDirection::In, args[1]);

            Console::WriteLine("[CLIENT] Current TransmissionMode: {0}.",
                pipeClient->TransmissionMode);

            StreamReader^ sr = gcnew StreamReader(pipeClient);

            // Display the read text to the console
            String^ temp;

            // Wait for 'sync message' from the server.
            do
            {
                Console::WriteLine("[CLIENT] Wait for sync...");
                temp = sr->ReadLine();
            }
            while (!temp->StartsWith("SYNC"));

            // Read the server data and echo to the console.
            while ((temp = sr->ReadLine()) != nullptr)
            {
                Console::WriteLine("[CLIENT] Echo: " + temp);
            }
            sr->Close();
            pipeClient->Close();
        }
        Console::Write("[CLIENT] Press Enter to continue...");
        Console::ReadLine();
    }
};

int main()
{
    array<String^>^ args = Environment::GetCommandLineArgs();
    PipeClient::Main(args);
}
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("[CLIENT] Current TransmissionMode: {0}.",
                   pipeClient.TransmissionMode);

                using (StreamReader sr = new StreamReader(pipeClient))
                {
                    // Display the read text to the console
                    string temp;

                    // Wait for 'sync message' from the server.
                    do
                    {
                        Console.WriteLine("[CLIENT] Wait for sync...");
                        temp = sr.ReadLine();
                    }
                    while (!temp.StartsWith("SYNC"));

                    // Read the server data and echo to the console.
                    while ((temp = sr.ReadLine()) != null)
                    {
                        Console.WriteLine("[CLIENT] Echo: " + temp);
                    }
                }
            }
        }
        Console.Write("[CLIENT] Press Enter to continue...");
        Console.ReadLine();
    }
}
Imports System.IO
Imports System.IO.Pipes

Class PipeClient
    Shared Sub Main(args() as String)
        If args.Length > 0 Then
            Using pipeClient As New AnonymousPipeClientStream(PipeDirection.In, args(0))
                Console.WriteLine("[CLIENT] Current TransmissionMode: {0}.", _
                   pipeClient.TransmissionMode)

                Using sr As New StreamReader(pipeClient)
                    ' Display the read text to the console
                    Dim temp As String

                    ' Wait for 'sync message' from the server.
                    Do
                        Console.WriteLine("[CLIENT] Wait for sync...")
                        temp = sr.ReadLine()
                    Loop While temp.StartsWith("SYNC") = False

                    ' Read the server data and echo to the console.
                    temp = sr.ReadLine()
                    While Not temp = Nothing
                        Console.WriteLine("[CLIENT] Echo: " + temp)
                        temp = sr.ReadLine()
                    End While
                End Using
            End Using
        End If
        Console.Write("[CLIENT] Press Enter to continue...")
        Console.ReadLine()
    End Sub
End Class

另請參閱