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)
13601정성태4/19/2024196닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024276닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024301닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024336닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024397닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024774닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024896닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241016닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241050닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241207C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241169닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241073Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241143닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241197닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241156오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241297Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241096Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241048개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241158Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241420Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241587개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241137닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241494오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241629닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241875닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...