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

비밀번호

댓글 작성자
 




... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13541정성태1/29/20249610VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20249499Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20249306개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20249901닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/202410685닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/202410300닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/202410726닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/202410140닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/202410122닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/202410175닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/202410556닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20249835닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/202410035닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/202410194Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/202410285오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/202410612닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20249751오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20249780오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20249767오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/202410598닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/202410255닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20249930오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....' [1]
13519정성태1/10/20249632닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/202410357닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20249502스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20249649닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...