다음을 통해 공유


방법: 익명 파이프를 사용하여 로컬 프로세스 간 통신

업데이트: 2007년 11월

익명 파이프는 명명된 파이프보다 적은 기능을 제공하지만 오버로드를 더 적게 필요로 합니다. 익명 파이프를 사용하면 로컬 컴퓨터에서 프로세스 간 통신을 보다 쉽게 수행할 수 있습니다. 네트워크를 통한 통신에는 익명 파이프를 사용할 수 없습니다.

예제

다음 예제에서는 익명 파이프를 사용하여 부모 프로세스에서 자식 프로세스로 문자열을 보내는 방법을 보여 줍니다. 이 예제에서는 PipeDirectionOut을 사용하여 부모 프로세스에 AnonymousPipeServerStream 개체를 만듭니다. 그러면 부모 프로세스는 클라이언트 핸들을 통해 AnonymousPipeClientStream 개체를 만들어 자식 프로세스를 만듭니다. 자식 프로세스는 In의 값으로 PipeDirection을 갖습니다.

다음으로 부모 프로세스는 자식 프로세스에 사용자 제공 문자열을 보냅니다. 이 문자열은 자식 프로세스의 콘솔에 표시됩니다.

다음 예제에서는 서버 프로세스를 보여 줍니다.

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

참고 항목

작업

방법: 명명된 파이프를 사용하여 네트워크를 통한 프로세스 간 통신

개념

파이프