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)
13373정성태6/19/20234398오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
13372정성태6/15/20233111개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233132개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233296개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233094개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233225개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233333오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233130.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20232896오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233678.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233242스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233164.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233638오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233037오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233354오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233660.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233464.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233769DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233685.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20233958.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233569.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234072VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233323오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233661.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233570.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20233933.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...