Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)
(시리즈 글이 10개 있습니다.)
Windows: 63. 윈도우 서버 2012 - Hyper-V의 새로운 기능 Live Migration
; https://www.sysnet.pe.kr/2/0/1356

개발 환경 구성: 211. Hyper-V - Generation 2 유형의 VM 생성 시 ISO 부팅이 안된다면?
; https://www.sysnet.pe.kr/2/0/1603

개발 환경 구성: 236. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법
; https://www.sysnet.pe.kr/2/0/1742

개발 환경 구성: 317. Hyper-V 내의 VM에서 다시 Hyper-V를 설치: Nested Virtualization
; https://www.sysnet.pe.kr/2/0/11218

개발 환경 구성: 405. Hyper-V 가상 머신에서 직렬 포트(Serial Port, COM Port) 사용
; https://www.sysnet.pe.kr/2/0/11720

.NET Framework: 798. C# - Hyper-V 가상 머신의 직렬 포트와 연결된 Named Pipe 간의 통신
; https://www.sysnet.pe.kr/2/0/11722

디버깅 기술: 169. Hyper-V의 VM에 대한 메모리 덤프를 뜨는 방법
; https://www.sysnet.pe.kr/2/0/12284

개발 환경 구성: 608. Hyper-V 가상 머신에 Console 모드로 로그인하는 방법
; https://www.sysnet.pe.kr/2/0/12859

개발 환경 구성: 664. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/13246

Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
; https://www.sysnet.pe.kr/2/0/13564




C# - Hyper-V 가상 머신의 직렬 포트와 연결된 Named Pipe 간의 통신

지난 글에서 Hyper-V의 가상 머신에서 직렬 포트가 어떻게 설정되는지 설명했습니다.

Hyper-V 가상 머신에서 직렬 포트(Serial Port, COM Port) 사용
; https://www.sysnet.pe.kr/2/0/11720

사실 저렇게 매핑된 named pipe를 사용하는 대표적인 프로그램이 바로 windbg입니다.

Windbg - Hyper-V 윈도우 7 원격 디버깅 구성
; https://www.sysnet.pe.kr/2/0/938

혹시 windbg 말고, 우리도 저걸로 가상 머신 내의 COM 클라이언트와 통신할 수 있지 않을까요? 이를 위해 간단하게 테스트를 해봤습니다. 설정 방식은 간단합니다.

  • Host 측 프로그램은 Named Pipe Client 역할을 하고, Hyper-V가 열어 놓은 Named Pipe Server에 접속
  • VM 측 프로그램은 Serial Port Client 역할을 하고, VM에 연결된 COM Port에 접속

우선, Host 측 프로그램을 다음과 같이 간단하게 작성할 수 있습니다.

using System;
using System.IO.Pipes;
using System.Security.Principal;
using System.Text;

namespace PipeApp
{
    class Program
    {
        static void Main(string[] args)
        {
            NamedPipeClientStream pipeClient =
                    new NamedPipeClientStream(".", "myPipe2",
                        PipeDirection.InOut, PipeOptions.None,
                        TokenImpersonationLevel.Impersonation);

            pipeClient.Connect();
            Console.WriteLine("Connected...");

            while (true)
            {
                byte[] inBuffer = new byte[1024];
                int readBytes = 0;

                readBytes = pipeClient.Read(inBuffer, 0, 1024);

                string ascii = Encoding.ASCII.GetString(inBuffer, 0, readBytes);
                Console.Write(ascii);
            }

            pipeClient.Close();
        }
    }
}

위의 프로그램을 수행하는 호스트 측은 Hyper-V 내의 VM에 대해 COM 포트 중의 하나를 다음과 같이 PowerShell로 이름을 myPipe로 연결해 줘야 합니다.

PS C:\WINDOWS\system32> Set-VMComPort -VMName win10en -Path \\.\pipe\myPipe2 -Number 1

PS C:\WINDOWS\system32> Get-VMComPort -VMName win10en

VMName  Name  Path
------  ----  ----
win10en COM 1 \\.\pipe\myPipe2
win10en COM 2

그다음, VM 측에서는 제공되는 COM 1 포트에 접속해 단순 문자열을 전송하는 프로그램을 제작해 VM 내에서 실행합니다.

using System;
using System.IO.Ports;
using System.Runtime.InteropServices;
using System.Text;

namespace SerialPortApp
{
    class Program
    {
        static void Main(string[] args)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Console.WriteLine("On Windows");
                foreach (string portName in SerialPort.GetPortNames())
                {
                    SerialPort sps = new SerialPort(portName,
                        115200, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
                    sps.Open();

                    byte [] contents = Encoding.ASCII.GetBytes("test is good");
                    sps.Write(contents, 0, contents.Length);

                    sps.Close();
                    Console.WriteLine(portName);
                }
            }
        }
    }
}

만들어 놓고 보니 간단하군요. ^^ 실행해보면 정상적으로 통신이 되는 것을 확인할 수 있습니다.

그렇다면, 리눅스 VM의 경우에는 어떨까요? 일례로, Hyper-V의 MobyLinuxVM인 경우에도 "/dev/ttyS0"은 이미 docker에서 점유하고 있으므로 "/dev/ttyS1"의 SerialPort를 열어,

if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
    Console.WriteLine("On Linux");
    foreach (string portName in SerialPortStream.GetPortNames())
    {
        // Hyper-V 가상머신이 아닌, 물리 PC의 리눅스 머신으로 하면 /dev/ttyUSB0과 같은 식의 이름으로 됩니다.
        if (portName == "/dev/ttyS1")
        {
            SerialPortStream sps = new SerialPortStream(portName,
                115200, 8, RJCP.IO.Ports.Parity.None, RJCP.IO.Ports.StopBits.One);
            sps.Open();

            sps.WriteLine("test is good");
            sps.Flush();

            sps.Close();
        }

        Console.WriteLine(portName);
    }
}

통신하면 정상적으로 동작합니다.

(첨부 파일은 이 글의 예제를 포함합니다.)




참고로, 호스트 측의 named pipe 연결 프로그램 대신 putty를 이용해 다음과 같이 "Serial"로 설정 후 경로를 COM 포트 이름 대신 named pipe 형식으로 지정해도 됩니다.

hyperv_com_to_namedpipe_1.png




이를 활용하면, Hyper-V를 호스팅하는 물리 컴퓨터에 꽂힌 Serial 장비를 VM 내에서 제어하는 것이 가능합니다. 즉, 호스트 측에서 실행하는 중계 프로그램을 하나 만들어 VM 내의 Serial 제어를 named pipe로부터 받아 물리 장비에 연결된 Serial 장치에 전달할 수 있는 것입니다.

그런데... 아마도 위의 중계 프로그램을 굳이 만들 필요는 없을 것 같습니다. 테스트하진 않았는데 아마 다음의 프로그램이 그러한 역할을 해주는 프로그램으로 보입니다. ^^

albertjan/PipeToCom 
    - Couple your Hyper-V namedpipe comport to a real one. 
; https://github.com/albertjan/PipeToCom




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 10/4/2018]

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

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  69  70  71  72  [73]  74  75  ...
NoWriterDateCnt.TitleFile(s)
11820정성태2/20/201915231오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201913903Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201912814VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/20199970오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201912477Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201911363오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201910199오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201911801.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/20199626오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201913415오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
11810정성태2/11/201911466.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
11809정성태2/11/201912985.NET Framework: 807. ClrMD를 이용해 메모리 덤프 파일로부터 특정 인스턴스를 참조하고 있는 소유자 확인
11808정성태2/8/201914048디버깅 기술: 123. windbg - 닷넷 응용 프로그램의 메모리 누수 분석
11807정성태1/29/201912357Windows: 156. 가상 디스크의 용량을 복구 파티션으로 인해 늘리지 못하는 경우 [4]
11806정성태1/29/201912104디버깅 기술: 122. windbg - 덤프 파일로부터 PID와 환경 변수 등의 정보를 구하는 방법
11805정성태1/28/201913938.NET Framework: 806. C# - int []와 object []의 차이로 이해하는 제네릭의 필요성 [4]파일 다운로드1
11804정성태1/24/201911977Windows: 155. diskpart - remove letter 이후 재부팅 시 다시 드라이브 문자가 할당되는 경우
11803정성태1/10/201911480디버깅 기술: 121. windbg - 닷넷 Finalizer 스레드가 멈춰있는 현상
11802정성태1/7/201912848.NET Framework: 805. 두 개의 윈도우를 각각 실행하는 방법(Windows Forms, WPF)파일 다운로드1
11801정성태1/1/201913902개발 환경 구성: 427. Netsh의 네트워크 모니터링 기능 [3]
11800정성태12/28/201813176오류 유형: 509. WCF 호출 오류 메시지 - System.ServiceModel.CommunicationException: Internal Server Error
11799정성태12/19/201813991.NET Framework: 804. WPF(또는 WinForm)에서 UWP UI 구성 요소 사용하는 방법 [3]파일 다운로드1
11798정성태12/19/201813219개발 환경 구성: 426. vcpkg - "Building vcpkg.exe failed. Please ensure you have installed Visual Studio with the Desktop C++ workload and the Windows SDK for Desktop C++"
11797정성태12/19/201810580개발 환경 구성: 425. vcpkg - CMake Error: Problem with archive_write_header(): Can't create '' 빌드 오류
11796정성태12/19/201810228개발 환경 구성: 424. vcpkg - "File does not have expected hash" 오류를 무시하는 방법
11795정성태12/19/201812652Windows: 154. PowerShell - Zone 별로 DNS 레코드 유형 정보 조회 [1]
... 61  62  63  64  65  66  67  68  69  70  71  72  [73]  74  75  ...