Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

(시리즈 글이 6개 있습니다.)
.NET Framework: 480. C# - 배치 파일 실행하고 출력 결과를 얻는 방법
; https://www.sysnet.pe.kr/2/0/1810

.NET Framework: 602. Process.Start의 cmd.exe에서 stdin만 redirect 하는 방법
; https://www.sysnet.pe.kr/2/0/11029

.NET Framework: 817. Process.Start로 실행한 콘솔 프로그램의 출력 결과를 얻는 방법
; https://www.sysnet.pe.kr/2/0/11870

Linux: 24. Linux/C# - 실행 파일이 아닌 스크립트 형식의 명령어를 Process.Start로 실행하는 방법
; https://www.sysnet.pe.kr/2/0/12073

닷넷: 2292. C# - 자식 프로세스의 출력이 4,096보다 많은 경우 Process.WaitForExit 호출 시 hang 현상
; https://www.sysnet.pe.kr/2/0/13707

닷넷: 2314. C# - ProcessStartInfo 타입의 Arguments와 ArgumentList
; https://www.sysnet.pe.kr/2/0/13876




C# - 자식 프로세스의 출력이 4,096보다 많은 경우 Process.WaitForExit 호출 시 hang 현상

재현 코드를 만들어 볼까요? ^^

우선, 자식 프로세스를 실행하는 코드는 이렇게 RedirectStandardOutput = true로 설정했을 때입니다.

using System.Diagnostics;

internal class Program
{
    static void Main(string[] args)
    {
        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = "ConsoleApp2.exe";
        psi.UseShellExecute = false; /* 닷넷 프레임워크의 경우 기본값이 true */
        psi.RedirectStandardOutput = true;

        Process? process = Process.Start(psi);
        if (process != null)
        {
            TimeSpan waitTime = TimeSpan.FromSeconds(3);
            if (process.WaitForExit((int)waitTime.TotalMilliseconds) == false)
            {
                Console.WriteLine($"# Timeout: {waitTime}");
                return;
            }

            string result = process.StandardOutput.ReadToEnd();
            Console.WriteLine(result);
        }
    }
}

그리고 실행되는 자식 프로세스는 콘솔에 4K + 1 문자열을 출력합니다.

internal class Program
{
    static void Main(string[] args)
    {
        string text = new string('a', 1024 * 3 + 1024 + 1); // 4096 + 1 문자열 출력
        Console.Write(text);
    }
}

위와 같이 코드를 작성하고 실행하면, 부모 프로세스에서 WaitForExit를 호출했을 때 hang 현상이 발생하고, 설정해 두었던 10초가 지나서야 timeout으로 벗어나게 됩니다.

왜 이런 걸까요? ^^




이 현상은 서버에서 Redirect로 받아주는 Output 버퍼가 4096 바이트로 제한돼 있기 때문입니다. (있기 때문으로 보입니다. ^^)

그래서인지, 자식 프로세스는 4096 바이트를 넘는 출력을 하면 부모가 할당해 준 버퍼가 꽉 차게 돼 이후 여유 버퍼가 생길 때까지 기다리게 되고, 반대로 서버 측은 그것을 읽지 않아서 버퍼가 가득 찬 상태로 계속 자식 프로세스가 종료하기를 기다리게 되는 것입니다.

이 문제를 해결하려면, 부모 측에서 WaitForExit에 앞서 Read 동작을 수행해 주면 됩니다.

Process? process = Process.Start(psi);
if (process != null)
{
    string result = process.StandardOutput.ReadToEnd();
    Console.WriteLine(result);

    if (process.ExitCode != 0)
    {
        Console.WriteLine($"# ExitCode: {process.ExitCode}");
        return;
    }
}

ReadToEnd는 프로세스가 종료될 때까지 출력을 읽어들이기 때문에 저런 경우 굳이 WaitForExit를 호출하지 않아도 됩니다.




그런데, 가끔은 자식 프로세스의 종료를 특정하고 싶을 때가 있습니다. 가령, 3초 이상 걸린다면 그냥 읽기를 포기하는 것입니다. 그런데, 위와 같이 처리하는 경우에는 그것이 안 됩니다. 재현을 위해 자식 프로세스에 다음과 같이 코드를 추가하면,

internal class Program
{
    static void Main(string[] args)
    {
        string text = new string('a', 1024 * 3 + 1024 + 1);
        Console.Write(text);

        Thread.Sleep(-1);
    }
}

이후 부모 프로세스는 ReadToEnd에서 무한 대기를 하게 됩니다. 아쉽게도 만료 시간을 지정할 수 있었던 WaitForExit와는 달리 ReadToEnd는 그게 없는 건데요, 검색해 보면 BeginOutputReadLine을 곁들이면 된다고 나옵니다.

Process.BeginOutputReadLine Method
; https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.beginoutputreadline

위의 문서에 나온 예제대로 코드를 작성해,

Process? process = Process.Start(psi);
if (process != null)
{
    StringBuilder sb = new StringBuilder();

    process.OutputDataReceived += (sender, args) =>
    {
        sb.Append(args.Data);
    };

    process.BeginOutputReadLine();

    TimeSpan waitTime = TimeSpan.FromSeconds(3);
    if (process.WaitForExit((int)waitTime.TotalMilliseconds) == false)
    {
        Console.WriteLine($"# Output: {sb}"); // 언제나 sb == 빈 문자열
        return;
    }

    Console.Write($"# Output: {sb}"); // 언제나 sb == 빈 문자열

    if (process.HasExited == true && process.ExitCode != 0)
    {
        Console.WriteLine($"# ExitCode: {process.ExitCode}");
        return;
    }
}

실제로 실행해 보면, 자식 프로세스가 timeout이든 아니든 출력은 "# Output: "만 나옵니다. 가만 보니까, OutputDataReceived 이벤트 핸들러는 timeout이 아닌 경우, 즉 정상 출력을 마치고 종료한 경우에만 실행이 되었는데요, 그 실행 시점이 이상합니다. 즉, 실행 중에 이벤트 핸들러가 불리지 않고 (이후 부모 프로세스 측에서) "Console.Write"를 호출한 시점에 불리는데요, 아쉽게도 sb.ToString 평가는 그전에 끝나서 결과를 반영하지 못합니다. 이 문제를 해결하려면 더미로 그전에 Console.Write('\0')와 같은 호출을 하나 넣어주면 되는데, 테스트해 보니까 Console.Out.Flush를 해도 실행은 되므로 다음과 같이 코드를 보완할 수 있습니다.

TimeSpan waitTime = TimeSpan.FromSeconds(3);
if (process.WaitForExit((int)waitTime.TotalMilliseconds) == false)
{
    Console.WriteLine($"# Output: {sb}"); // 언제나 sb == 빈 문자열
    return;
}

Console.Out.Flush(); // 이 코드를 호출하는 순간 OutputDataReceived 콜백 발생
Console.Write($"# Output: {sb}"); // 자식 프로세스가 출력한 내용

그래도 timeout이 발생한 경우의 출력은 받아오지 못합니다. 하지만, 그렇다고 해서 자식 프로세스로부터 출력을 받지 못한 것은 아닙니다. 만약, 받지 못했다면 자식 프로세스는 Thread.Sleep(-1) 호출이 아닌 Console.Write(4096 + 1) 코드에서 멈췄을 것입니다.

실제로, Visual Studio를 이용해 디버거로 확인해 보면, Process 타입에 .NET Framework의 경우 output, .NET Core/5+의 경우 _output이라는 System.Diagnostics.AsyncStreamReader 타입의 필드가 있고,

/System/services/monitoring/system/diagnosticts/AsyncStreamReader.cs
; https://github.com/microsoft/referencesource/blob/master/System/services/monitoring/system/diagnosticts/AsyncStreamReader.cs

이 저장소에는 자식 프로세스가 그 시점까지 출력했던 내용이 담겨 있습니다. 따라서, Reflection을 사용한다면 이런 식으로 값을 가져올 수는 있습니다.

TimeSpan waitTime = TimeSpan.FromSeconds(3);
if (process.WaitForExit((int)waitTime.TotalMilliseconds) == false)
{
    Console.WriteLine($"# Timeout: {waitTime}");

    // .NET Framework
    // string text = ReadAsyncStreamReader(process, "output", "sb");

    // .NET Core/5+
    string text = ReadAsyncStreamReader(process, "_output", "_sb");
    Console.WriteLine($"# Output: {text}");
    return;
}

private static string ReadAsyncStreamReader(Process process, string outputFieldName, string sbFieldName)
{
    FieldInfo fi = typeof(Process).GetField(outputFieldName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
    if (fi == null)
    {
        return "";
    }

    object objOutput = fi.GetValue(process);
    if (objOutput == null)
    {
        return "";
    }

    fi = objOutput.GetType().GetField(sbFieldName, BindingFlags.NonPublic | BindingFlags.Instance);
    if (fi == null)
    {
        return "";
    }

    object objText = fi.GetValue(objOutput);
    if (objText == null)
    {
        return "";
    }

    return objText.ToString();
}




만약 .NET Core 2.1 이상을 사용하고 있다면, 다행히 더 좋은 방법이 있습니다. 바로 StandardOutput.ReadAsync 비동기 메서드를 사용하는 것인데요, 그럼 이렇게 코드를 만들 수 있습니다.

static async Task Main(string[] args)
{
    ProcessStartInfo psi = new ProcessStartInfo();
    psi.FileName = "ConsoleApp2.exe";
    psi.RedirectStandardOutput = true;

    Process? process = Process.Start(psi);
    if (process != null)
    {
        try
        {
            StringBuilder sb = new StringBuilder();

            Memory<char> buffer = new Memory<char>(new char[4096]);
            CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(TimeSpan.FromSeconds(3));

            while (true)
            {
                try
                {
                    int readBytes = await process.StandardOutput.ReadAsync(buffer, cts.Token);
                    if (readBytes == 0)
                    {
                        break;
                    }
                }
                catch
                {
                    break;
                }

                sb.Append(buffer.ToString());
            }

            Console.Write($"# Output: {sb}");

            if (process.HasExited && process.ExitCode != 0)
            {
                Console.WriteLine($"# ExitCode: {process.ExitCode}");
                return;
            }
        }
        finally
        {
            process.Dispose();
        }
    }
}

위의 경우, 자식 프로세스 실행 시 timeout이든 아니든 그에 상관없이 ReadAsync를 호출해 받아온 출력까지는 모두 구할 수 있습니다.

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





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







[최초 등록일: ]
[최종 수정일: 8/6/2024]

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

비밀번호

댓글 작성자
 




... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
13162정성태11/15/202215708.NET Framework: 2069. .NET 7 - AOT(ahead-of-time) 컴파일 [1]
13161정성태11/14/202214351.NET Framework: 2068. C# - PublishSingleFile로 배포한 이미지의 역어셈블 가능 여부 (난독화 필요성) [4]
13160정성태11/11/202214310.NET Framework: 2067. C# - PublishSingleFile 적용 시 native/managed 모듈 통합 옵션
13159정성태11/10/202217636.NET Framework: 2066. C# - PublishSingleFile과 관련된 옵션 [3]
13158정성태11/9/202213326오류 유형: 826. Workload definition 'wasm-tools' in manifest 'microsoft.net.workload.mono.toolchain' [...] conflicts with manifest 'microsoft.net.workload.mono.toolchain.net7'
13157정성태11/8/202214365.NET Framework: 2065. C# - Mutex의 비동기 버전파일 다운로드1
13156정성태11/7/202215960.NET Framework: 2064. C# - Mutex와 Semaphore/SemaphoreSlim 차이점파일 다운로드1
13155정성태11/4/202214196디버깅 기술: 183. TCP 동시 접속 (연결이 아닌) 시도를 1개로 제한한 서버
13154정성태11/3/202214682.NET Framework: 2063. .NET 5+부터 지원되는 GC.GetGCMemoryInfo파일 다운로드1
13153정성태11/2/202215997.NET Framework: 2062. C# - 코드로 재현하는 소켓 상태(SYN_SENT, SYN_RECV)
13152정성태11/1/202214893.NET Framework: 2061. ASP.NET Core - DI로 추가한 클래스의 초기화 방법 [1]
13151정성태10/31/202214350C/C++: 161. Windows 11 환경에서 raw socket 테스트하는 방법파일 다운로드1
13150정성태10/30/202213244C/C++: 160. Visual Studio 2022로 빌드한 C++ 프로그램을 위한 다른 PC에서 실행하는 방법
13149정성태10/27/202213816오류 유형: 825. C# - CLR ETW 이벤트 수신이 GCHeapStats_V1/V2에 대해 안 되는 문제파일 다운로드1
13148정성태10/26/202213746오류 유형: 824. msbuild 에러 - error NETSDK1005: Assets file '...\project.assets.json' doesn't have a target for 'net5.0'. Ensure that restore has run and that you have included 'net5.0' in the TargetFramew
13147정성태10/25/202213013오류 유형: 823. Visual Studio 2022 - Unable to attach to CoreCLR. The debugger's protocol is incompatible with the debuggee.
13146정성태10/24/202214323.NET Framework: 2060. C# - Java의 Xmx와 유사한 힙 메모리 최댓값 제어 옵션 HeapHardLimit
13145정성태10/21/202214959오류 유형: 822. db2 - Password validation for user db2inst1 failed with rc = -2146500508
13144정성태10/20/202214654.NET Framework: 2059. ClrMD를 이용해 윈도우 환경의 메모리 덤프로부터 닷넷 모듈을 추출하는 방법파일 다운로드1
13143정성태10/19/202215602오류 유형: 821. windbg/sos - Error code - 0x000021BE
13142정성태10/18/202220386도서: 시작하세요! C# 12 프로그래밍
13141정성태10/17/202216127.NET Framework: 2058. [in,out] 배열을 C#에서 C/C++로 넘기는 방법 - 세 번째 이야기파일 다운로드1
13140정성태10/11/202215526C/C++: 159. C/C++ - 리눅스 환경에서 u16string 문자열을 출력하는 방법 [2]
13139정성태10/9/202213611.NET Framework: 2057. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 모든 닷넷 모듈을 추출하는 방법파일 다운로드1
13138정성태10/8/202216202.NET Framework: 2056. C# - await 비동기 호출을 기대한 메서드가 동기로 호출되었을 때의 부작용 [1]
13137정성태10/8/202214130.NET Framework: 2055. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 닷넷 모듈을 추출하는 방법
... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...