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)
13429정성태10/27/20232923닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20232981닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233157닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233324스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233140닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233119스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233274닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233319닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235474스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233148스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233843닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233400닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233186오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233677닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233447디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233642닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20236922닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233416Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20234932닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233790닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233767Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233516닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233477VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
13405정성태9/3/20233921닷넷: 2138. C# - async 메서드 호출 원칙
13404정성태8/29/20233432오류 유형: 876. Windows - 키보드의 등호(=, Equals sign) 키가 눌리지 않는 경우
13403정성태8/21/20233265오류 유형: 875. The following signatures couldn't be verified because the public key is not available: NO_PUBKEY EB3E94ADBE1229CF
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...