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
정성태

... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13227정성태1/23/20234873개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234553.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20233802개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234149Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/20234346오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/20234001개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/20234243Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/20234371오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/20233936Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/20233876VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/20234467디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/20234718디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/20236266Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/20235825.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/20235375오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/20235124기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
13211정성태1/6/20235148웹: 42. (https가 아닌) http 다운로드를 막는 웹 브라우저
13210정성태1/5/20234205Windows: 219. 윈도우 x64의 경우 0x00000000`7ffe0000 아래의 주소는 왜 사용하지 않을까요?
13209정성태1/4/20234094Windows: 218. 왜 윈도우에서 가상 메모리 공간은 64KB 정렬이 된 걸까요?
13208정성태1/3/20234057.NET Framework: 2086. C# - Windows 운영체제의 2MB Large 페이지 크기 할당 방법파일 다운로드1
13207정성태12/26/20224360.NET Framework: 2085. C# - gpedit.msc의 "User Rights Assignment" 특권을 코드로 설정/해제하는 방법파일 다운로드1
13206정성태12/24/20224584.NET Framework: 2084. C# - GetTokenInformation으로 사용자 SID(Security identifiers) 구하는 방법 [3]파일 다운로드1
13205정성태12/24/20224936.NET Framework: 2083. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용 (2)파일 다운로드1
13204정성태12/22/20224221.NET Framework: 2082. C# - (LSA_UNICODE_STRING 예제로) CustomMarshaler 사용법파일 다운로드1
13203정성태12/22/20224385.NET Framework: 2081. C# Interop 예제 - (LSA_UNICODE_STRING 예제로) 구조체를 C++에 전달하는 방법파일 다운로드1
13202정성태12/21/20224799기타: 84. 직렬화로 설명하는 Little/Big Endian파일 다운로드1
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...