次の方法で共有


方法: ローカルプロセス間通信に匿名パイプを使用する

匿名パイプは、ローカル コンピューター上のプロセス間通信を提供します。 名前付きパイプよりも少ない機能を提供しますが、必要なオーバーヘッドも少なくなります。 匿名パイプを使用すると、ローカル コンピューターでのプロセス間通信を容易にすることができます。 ネットワーク経由の通信に匿名パイプを使用することはできません。

匿名パイプを実装するには、AnonymousPipeServerStream クラスと AnonymousPipeClientStream クラスを使用します。

例 1

次の例は、匿名パイプを使用して親プロセスから子プロセスに文字列を送信する方法を示しています。 次の使用例は、AnonymousPipeServerStream 値が PipeDirectionの親プロセスに Out オブジェクトを作成します。その後、親プロセスは、クライアント ハンドルを使用して子プロセスを作成し、AnonymousPipeClientStream オブジェクトを作成します。 子プロセスの PipeDirection 値は Inです。

その後、親プロセスは、ユーザー指定の文字列を子プロセスに送信します。 この文字列は、子プロセスでコンソールに表示されます。

次の例は、サーバー プロセスを示しています。

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: {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: {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;
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: {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

こちらもご覧ください