Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 4개 있습니다.)
.NET Framework: 199. .NET 코드 - Named Pipe 닷넷 서버와 VC++ 클라이언트 제작
; https://www.sysnet.pe.kr/2/0/971

.NET Framework: 464. 프로세스 간 통신 시 소켓 필요 없이 간단하게 Pipe를 열어 통신하는 방법
; https://www.sysnet.pe.kr/2/0/1751

.NET Framework: 477. SeCreateGlobalPrivilege 특권과 WCF NamedPipe
; https://www.sysnet.pe.kr/2/0/1806

Linux: 20. C# - Linux에서의 Named Pipe를 이용한 통신
; https://www.sysnet.pe.kr/2/0/11964




프로세스 간 통신 시 소켓 필요 없이 간단하게 Pipe를 열어 통신하는 방법

Named Pipe가 .NET 3.5부터 NamedPipeServerStream / NamedPipeClientStream 객체를 통해 제공됩니다. 여건이 된다면 이것을 사용하는 것이 가장 좋고 관련해서 예제도 MSDN에 잘 공개되어 있습니다.

하지만, 범용 라이브러리 제작사의 경우에는 .NET 2.0을 포함시켜야 하는 상황이 종종 발생하므로 P/Invoke를 이용해 Win32 API를 직접 호출해서 파이프 통신을 구현할 수 있습니다.

왜 파이프 통신을 사용하는 걸까요? 사실, 프로세스 간에 간단하게 통신이 필요한 경우 소켓을 이용하자니 포트의 관리가 귀찮습니다. 고정 포트를 둬도 되겠지만 역시나 라이브러리 제작사에서는 포트를 위한 별도의 관리 지점을 만들어야 합니다. 바로 이럴 때! 그냥 Named Pipe를 쓰면 고민거리가 사라져버립니다.

찾아보면, CreateFile, CreateNamedPipe, ConnectNamedPipe, DisconnectNamedPipe API를 직접 이용해서 구현한 C# 예제가 있습니다.

Interprocess Communication using Named Pipes in C#
; http://tech.pro/tutorial/633/interprocess-communication-using-named-pipes-in-csharp

기반은 위의 소스코드를 가져다 썼고, 그래도 개인적으로 개선해보았습니다.

우선, 클라이언트로부터의 연결 대기를 동기에서 비동기로 바꿨습니다. 이를 위해 ConnectNamedPipe에 Win32 Overlapped 구조체를 전달했습니다. (Overlapped 사용 방법 예제 참조)

NativeOverlapped overlapped = new NativeOverlapped();

using (EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.ManualReset, ...))
{
    overlapped.EventHandle = ewh.SafeWaitHandle.DangerousGetHandle();

    ConnectNamedPipe(clientPipe._pipeHandle, ref overlapped);
    int lastError = Marshal.GetLastWin32Error();

    //...[생략]...
}

그런데, 재미있는 것은 지금부터입니다. 비동기로 했으므로 ConnectNamedPipe는 곧바로 제어를 반환하게 되고 이후 lastError == ERROR_IO_PENDING 값이면 대기를 할 수 있는 동작을 하게 됩니다.

if (lastError == 997) // #define ERROR_IO_PENDING 997L 
{
    int completeCode = 0;
                    
    WaitHandle[] waitHandles = new WaitHandle[] { ewh, _exitEvent };
    completeCode = WaitHandle.WaitAny(waitHandles, Timeout.Infinite, false);

    if (completeCode == 0) // connect completely
    {
    }
    else if (completeCode == 1) // Server.Dispose
    {
        Trace.WriteLine("(Dispose) End of PipeService");
        clientPipe.Dispose();
        return null;
    }
}
else if (lastError != 535) // #define ERROR_PIPE_CONNECTED 535L
{
    Trace.WriteLine("Pipe Connect Error: " + lastError);
    clientPipe.Dispose();
    return null;
}
else
{
    // ERROR_PIPE_CONNECTED
    Debug.WriteLine("Connected");
}

그런데, 유독 "x64/.NET 2.0" 조합으로 빌드하는 경우 클라이언트가 연결되어 WaitHandle.WaitAny의 대기가 풀리게 되는 내부 코드에서 비정상 종료가 발생합니다. (x86/.NET 2.0에서는 OK!) 이때 이벤트 로그는 다음과 같은 기록이 남습니다.

Log Name:      Application
Source:        Windows Error Reporting
Date:          2014-09-20 오후 3:05:39
Event ID:      1001
Task Category: None
Level:         Information
Keywords:      Classic
User:          N/A
Computer:      TESTPC2
Description:
Fault bucket 81722438277, type 5
Event Name: BEX64
Response: Not available
Cab Id: 0

Problem signature:
P1: PipeServer.exe
P2: 1.0.0.0
P3: 541d113f
P4: mscorwks.dll
P5: 2.0.50727.8009
P6: 53a1205c
P7: 00000000006b0bbb
P8: c0000409
P9: 0000000000000000
P10: 

Attached files:
c:\...\AppData\Local\Temp\WERB77B.tmp.WERInternalMetadata.xml
c:\...\AppData\Local\Temp\WERBBF1.tmp.appcompat.txt

These files may be available here:
c:\...\AppData\Local\Microsoft\Windows\WER\ReportArchive\AppCrash_PipeServer.exe_6c8b5291e79e5faa45279476aec0c352b46de1b_f845d3a1_04a8bc00

Analysis symbol: 
Rechecking for solution: 0
Report Id: 23c94c7c-408c-11e4-82e5-b81809256582
Report Status: 1
Hashed bucket: d459af57af1f50a06f32b72cb4a2ea59

mscorwks.dll 파일은 native DLL이기 때문에 더 파고 들 수가 없군요. ^^; 여기서 더욱 재미있는 점은, WaitAny가 아닌 단일 이벤트 대기를 하는 경우에는 비정상 종료가 안되었습니다.

// 오류 발생하지 않음.
ewh.WaitOne();

// 하지만, WaitAny를 통하면 이벤트가 하나여도 오류 발생
WaitHandle[] waitHandles = new WaitHandle[] { ewh };
completeCode = WaitHandle.WaitAny(waitHandles, Timeout.Infinite, false);

혹시나 싶어, Win32 P/Invoke로 직접 대기를 했더니 이번에는 예외가 발생하지 않습니다.

[DllImport("kernel32.dll")]
static extern int WaitForMultipleObjects(int nCount, IntPtr[] lpHandles, bool bWaitAll, int dwMilliseconds);

// ... 

IntPtr[] waitHandles2 = new IntPtr[] { ewh.Handle, _exitEvent.Handle };
completeCode = WaitForMultipleObjects(waitHandles.Length, waitHandles, false, -1);

일단 이걸로 넘어가겠습니다. ^^ (.NET 2.0 지원만 아니면 그냥 NamedPipeServerStream / NamedPipeClientStream으로 넘어가시는 것이 깔끔합니다.)

그런데, 저렇게 어차피 대기할 거면 뭐하러 비동기로 하는지 궁금하신 분들이 계실텐데요. 비동기의 장점은 꼭,,, 다른 작업을 가능하게 하는 것뿐만 아니라 부가적으로 '대기'를 원하는 시간에 언제든지 풀어버릴 수 있는 것도 가능하다는 점입니다.

예를 들어, 위의 비동기 작업을 그냥 동기로 처리해 버리면 ConnectNamedPipe에서 해당 스레드는 무한정 대기하게 되고, 나중에 이 작업이 필요없어졌을 때 취할 수 있는 방법이라고는 그 스레드를 강제 종료(Thread.Abort)하는 수 밖에는 없습니다. 즉, 곧바로 이어서 대기하는 비동기 작업의 경우 '우아한 종료' 작업을 가능케 하는 이점이 있습니다.

클라이언트 연결 대기를 비동기로 처리했으니, 이제 Read/Write 작업도 비동기로 해보겠습니다. 역시 이번에도 곧바로 대기 상태로 들어갈텐데요. 그래도 이렇게 함으로써 Read/Write 작업에 대한 time-out 설정을 할 수 있어서 좋습니다.

public string ReadString()
{
    return ReadString(Timeout.Infinite);
}

public string ReadString(int maxWaitMillisecond)
{
    if (CanRead == false || _pipeStream == null)
    {
        return "";
    }

    MemoryStream ms = new MemoryStream();
    UnicodeEncoding encoder = new UnicodeEncoding();

    byte[] buffer = new byte[BUFFER_SIZE];

    int bytesRead = 0;
    try
    {
        using (ManualResetEvent completed = new ManualResetEvent(false))
        {
            FileStream fsStream = _pipeStream;

            _pipeStream.BeginRead(buffer, 0, buffer.Length, (ar) =>
            {
                try
                {
                    bytesRead = fsStream.EndRead(ar);
                }
                catch { }

                if (completed.SafeWaitHandle.IsClosed == false)
                {
                    completed.Set();
                }
            }, null);

            int result = WaitHandle.WaitAny(new WaitHandle[] { completed, _exitEvent }, maxWaitMillisecond, false);

            try
            {
                if (result == 0) // read completely
                {
                }
                else if (result == 1) // by exit event
                {
                }
                else // timed-out
                {
                }
            }
            catch { }
        }
    }
    catch { }

    if (bytesRead == 0)
    {
        return "";
    }

    return encoder.GetString(buffer, 0, bytesRead);
}

public void WriteString(string message)
{
    WriteString(message, Timeout.Infinite);
}

public void WriteString(string message, int maxWaitMillisecond)
{
    if (CanWrite == false)
    {
        return;
    }

    UnicodeEncoding encoder = new UnicodeEncoding();
    byte[] sendBuffer = encoder.GetBytes(message);

    if (sendBuffer.Length > BUFFER_SIZE)
    {
        throw new ArgumentException("too large message");
    }

    try
    {
        using (ManualResetEvent completed = new ManualResetEvent(false))
        {
            FileStream fsStream = _pipeStream;
            _pipeStream.BeginWrite(sendBuffer, 0, sendBuffer.Length, (ar) =>
            {
                try
                {
                    fsStream.EndWrite(ar);
                }
                catch { }

                if (completed.SafeWaitHandle.IsClosed == false)
                {
                    completed.Set();
                }

            }, null);

            WaitHandle.WaitAny(new WaitHandle[] { completed, _exitEvent }, maxWaitMillisecond, false);
        }
    }
    catch { }
}

뭐... 이 정도면 대충 쓸만한 Pipe 통신이 되겠습니다. ^^

(첨부 파일은 위의 코드를 이용해 간단한 파이프 서버/클라이언트 통신을 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/17/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2024-03-08 08시49분
cyberark/PipeViewer
 - A tool that shows detailed information about named pipes in Windows
; https://github.com/cyberark/PipeViewer
정성태

1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13506정성태12/29/20232201닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232755닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232332닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232195Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232307닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232102개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232186디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20232868닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232300오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232319Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232328Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232509Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232604닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232302개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232239Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232359개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232144개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232074오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232392개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232206개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232092오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232168개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232306닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232885닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232275개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232631개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...