Procedura: utilizzare le unnamed pipe per la comunicazione tra i processi locali

Aggiornamento: novembre 2007

Le unnamed pipe offrono meno funzionalià rispetto alle named pipe ma richiedono meno overhead. È possibile utilizzarle per agevolare la comunicazione interprocesso su un computer locale. Non è possibile utilizzare le unnamed pipe per la comunicazione in una rete.

Esempio

Nell'esempio riportato di seguito viene illustrata una modalità per inviare una stringa da un processo padre a un processo figlio utilizzando le unnamed pipe. Viene creato un oggetto AnonymousPipeServerStream in un processo padre con un valore PipeDirection di Out. Il processo padre crea quindi un processo figlio utilizzando un handle del client per creare un oggetto AnonymousPipeClientStream. Il processo figlio ha un valore PipeDirection di In.

Il processo padre invia quindi una stringa fornita dall'utente al processo figlio. La stringa viene visualizzata nella console del processo figlio.

Nell'esempio riportato di seguito viene illustrato un processo server.

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();
    }
}

Nell'esempio riportato di seguito viene illustrato un processo client. Il processo server avvia il processo client e lo passa all'handle del client. Il file eseguibile risultante dal codice client deve essere denominato pipeClient.exe e copiato alla stessa directory del file eseguibile del server prima di eseguire il processo server.

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();
    }
}

Vedere anche

Attività

Procedura: utilizzare le named pipe per la comunicazione tra processi in rete

Concetti

Pipe