Microsoft MVP성태의 닷넷 이야기
.NET Framework: 602. Process.Start의 cmd.exe에서 stdin만 redirect 하는 방법 [링크 복사], [링크+제목 복사]
조회: 19224
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

Process.Start의 cmd.exe에서 stdin만 redirect 하는 방법

다음의 질문이 있군요.

System.Diagnostics.Process 를 이용해서 CMD(콘솔창)을 외부에서 컨트롤 하려고 합니다
; https://social.msdn.microsoft.com/Forums/ko-KR/aff886b6-7d34-4890-bc86-474d3f6d832b/systemdiagnosticsprocess-cmd-?forum=visualcsharpko

실제로 아래의 코드를 Windows Forms 응용 프로그램에서 실행해 보면,

private void Form1_Load(object sender, EventArgs e)
{
    Process pr = new Process();
    ProcessStartInfo pw = new ProcessStartInfo();

    pw.FileName = @"cmd.exe";
    pw.UseShellExecute = false;
    pw.RedirectStandardInput = true;
    pw.RedirectStandardOutput = true;

    pr.StartInfo = pw;

    pr.Start();
    pr.StandardInput.WriteLine(@"dir");
    pr.StandardInput.Close();

    string output = pr.StandardOutput.ReadToEnd();

    MessageBox.Show(output);

    pr.WaitForExit();
    pr.Close();
}

cmd.exe 실행 창이 뜨자마자 pr.StandardInput.Close();의 호출로 닫히면서 output 변수 값에는 cmd.exe 창에 출력되었을 내용들이 담겨 있습니다.

그런데, StandardInput만 redirect하고 StandardOutput을 cmd.exe 창으로 나타내고 싶다면 어떻게 해야 할까요? 즉, Windows Forms 응용 프로그램에서 cmd.exe 창에 실행되는 명령을 전달하고 출력을 cmd.exe 창 내에서 보고 싶은 것입니다.

이를 위해 다음과 같이 단순히 StandardOutput 쪽을 주석 처리해봤습니다.

private void Form1_Load(object sender, EventArgs e)
{
    Process pr = new Process();
    ProcessStartInfo pw = new ProcessStartInfo();

    pw.FileName = @"cmd.exe";
    pw.UseShellExecute = false;
    pw.RedirectStandardInput = true;
    // pw.RedirectStandardOutput = true;

    pr.StartInfo = pw;

    pr.Start();
    pr.StandardInput.WriteLine(@"dir");
    
    // pr.StandardInput.Close();
    // string output = pr.StandardOutput.ReadToEnd();
    // MessageBox.Show(output);

    pr.WaitForExit();
    pr.Close();
}

그랬더니, Input은 분명 redirect되었겠지만 StandardOutput을 변경하지 않았음에도 불구하고 화면에는 아무런 내용도 출력되지 않았습니다. 검색해 보면 다음의 문제가 바로 이에 해당합니다.

How can I start a process with stdin redirected, but not stdout?
; http://stackoverflow.com/questions/15547168/how-can-i-start-a-process-with-stdin-redirected-but-not-stdout

위의 질문을 했던 사람은 STARTF_USESTDHANDLES 옵션을 직접 지정해 주면 될 거라 생각하고 있는데,

STARTUPINFO structure- STARTF_USESTDHANDLES
; https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfoa

과연 그럴까요? ^^

.NET Reflector를 이용해 Process.Start를 보면,

public bool Start()
{
    this.Close();
    ProcessStartInfo startInfo = this.StartInfo;
    if (startInfo.FileName.Length == 0)
    {
        throw new InvalidOperationException(SR.GetString("FileNameMissing"));
    }
    if (startInfo.UseShellExecute)
    {
        return this.StartWithShellExecuteEx(startInfo);
    }
    return this.StartWithCreateProcess(startInfo);
}

우리의 상황에서는 UseShellExecute == false이기 때문에 StartWithCreateProcess를 호출하는 것을 볼 수 있습니다.

private bool StartWithCreateProcess(ProcessStartInfo startInfo)
{
    // ...[생략]...
    lock (obj2)
    {
        try
        {
            bool flag;
            if ((startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput) || startInfo.RedirectStandardError)
            {
                if (startInfo.RedirectStandardInput)
                {
                    this.CreatePipe(out parentHandle, out lpStartupInfo.hStdInput, true);
                }
                else
                {
                    lpStartupInfo.hStdInput = new SafeFileHandle(Microsoft.Win32.NativeMethods.GetStdHandle(-10), false);
                }
                if (startInfo.RedirectStandardOutput)
                {
                    this.CreatePipe(out handle4, out lpStartupInfo.hStdOutput, false);
                }
                else
                {
                    lpStartupInfo.hStdOutput = new SafeFileHandle(Microsoft.Win32.NativeMethods.GetStdHandle(-11), false);
                }
                if (startInfo.RedirectStandardError)
                {
                    this.CreatePipe(out handle5, out lpStartupInfo.hStdError, false);
                }
                else
                {
                    lpStartupInfo.hStdError = new SafeFileHandle(Microsoft.Win32.NativeMethods.GetStdHandle(-12), false);
                }
                lpStartupInfo.dwFlags = 0x100;
            }

            // ...[생략]...
        }
        finally
        {
            if (handle6.IsAllocated)
            {
                handle6.Free();
            }
            lpStartupInfo.Dispose();
        }
    }

    // ...[생략]...

    return flag2;
}

StartWithCreateProcess를 보면, RedirectStandardInput, RedirectStandardOutput, RedirectStandardError 중에서 어느 하나라도 redirect하라고 되어 있으면 새롭게 lpStartupInfo의 hStdInput, hStdOutput, hStdError 핸들을 모두 생성해 버립니다. 단지, 명시적으로 redirect 플래그가 true인 경우에는 CreatePipe로 Stream을 생성하고, false면 GetStdHandle로 받아온 -10, -11, -12를 대응시켜 생성합니다.

각각의 상수의 의미는 다음과 같습니다.

GetStdHandle function
; https://learn.microsoft.com/en-us/windows/console/getstdhandle

STD_INPUT_HANDLE == (DWORD)-10
STD_OUTPUT_HANDLE == (DWORD)-11
STD_ERROR_HANDLE == (DWORD)-12

소스 코드를 보고 나니, 왠지 RedirectStandardOutput == false인 경우라면 STD_OUTPUT_HANDLE이 지정되는 것이므로 더더욱 cmd.exe의 실행 창에 나타나야 하는 것이 맞지 않나 생각됩니다.

그런데, 한번 더 생각해 봐야 합니다. Process.Start 코드를 실행하는 프로세스는 Windows Forms 응용 프로그램이기 때문에 그 프로세스 내에서 GetStdHandle을 호출했다면 아직 뜨지 않은 cmd.exe가 아닌 Windows Forms 응용 프로그램의 표준 출력에 대한 핸들 값을 구해간 것입니다. 즉, cmd.exe의 표준 출력은 있지도 않은 Windows Forms의 STD_OUTPUT_HANDLE로 전송되었기 때문에 cmd.exe 창에는 아무것도 뜨지 않은 것입니다.

이렇게 해서 출력이 안되는 이유는 알았지만, 그런데 어떻게 자식 프로세스의 표준 출력을 부모 프로세스의 표준 출력으로 우회시키는 것이 가능한 걸까요? 원래 EXE 프로세스 간에는 격리가 되었으므로 Windows Forms 응용 프로그램의 HANDLE 값을 별도의 cmd.exe 프로세스에서 사용하는 것은 불가능합니다. 이쯤에서 StartWithCreateProcess 메서드의 lpStartupInfo.dwFlags = 0x100; 코드를 주목해 볼 필요가 있습니다.

dwFlags에 지정된 0x100은 STARTF_USESTDHANDLES 값입니다. 그렇습니다. "How can I start a process with stdin redirected, but not stdout?" 글의 질문자는 저 값을 일부러 지정하고 싶어 했지만 실제로는 RedirectStandardInput, RedirectStandardOutput, RedirectStandardError 중의 하나가 true 값이 되기만 하면 자동으로 지정되므로 별도 설정이 필요치 않은 것입니다.

그런데 이 플래그의 의미가 뭘까요?

STARTF_USESTDHANDLES - 0x00000100

The hStdInput, hStdOutput, and hStdError members contain additional information.
If this flag is specified when calling one of the process creation functions, the handles must be inheritable and the function's bInheritHandles parameter must be set to TRUE. For more information, see Handle Inheritance.


즉, STARTF_USESTDHANDLES 플래그를 지정하면 CreateProcess Win32 API 호출 시 bInheritHandles를 TRUE로 지정해서 실행하기 때문에 자식 프로세스에서 부모 프로세스의 표준 출력 핸들 값을 접근할 수 있었던 것입니다.




문제는 파악이 되었는데, 그럼 이 상황을 어떻게 해야 할까요?

간단합니다. Windows Forms 응용 프로그램에 표준 출력을 만들어주면 됩니다.

using System;
using System.Diagnostics;
using System.Windows.Forms;

using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool AllocConsole();

        public Form1()
        {
            InitializeComponent();
        }

        Process pr = new Process();

        private void Form1_Load(object sender, EventArgs e)
        {
            AllocConsole();
            ProcessStartInfo pw = new ProcessStartInfo();

            pw.FileName = @"cmd.exe";

            pw.UseShellExecute = false;
            pw.RedirectStandardInput = true;

            pr.StartInfo = pw;

            pr.Start();
            pr.StandardInput.WriteLine(@"dir");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            pr.StandardInput.WriteLine(this.textBox1.Text);
        }
    }
}

위와 같이 AllocConsole로 콘솔 기능을 만들어 주면 cmd.exe는 그 콘솔 창을 빌려 기능을 수행하게 됩니다. 주의할 것은 위의 프로그램을 Visual Studio 내에서 F5 디버깅으로 실행하면 안 된다는 점입니다. Visual Studio는 표준 출력을 자신의 디버깅 창으로 대체하기 때문에 cmd.exe의 출력이 "Output" 창에 나오게 됩니다.

따라서 Ctrl + F5 (Start Without Debugging)으로 실행하면 다음과 같이 Windows Forms에 입력한 명령을 cmd.exe에 전달하고 그 출력을 콘솔로 출력할 수 있습니다.

process_start_cmd_pipe_1.png

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





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

[연관 글]






[최초 등록일: ]
[최종 수정일: 3/22/2023]

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

비밀번호

댓글 작성자
 



2016-09-20 01시56분
[송기태] 와..ㅠㅠ 제질문에 선생님이 직접 달아주시니 정말 너무 감사합니다ㅠㅠ
[guest]

... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12427정성태11/24/20209956.NET Framework: 975. .NET Core를 직접 호스팅해 (runtimeconfig.json 없이) EXE만 배포해 실행파일 다운로드1
12426정성태11/24/20208568오류 유형: 685. WinDbg Preview - error InitTypeRead
12425정성태11/24/20209598VC++: 141. Visual C++ - "Treat Warnings As Errors" 옵션이 꺼져 있는데도 일부 경고가 에러 처리되는 경우
12424정성태11/24/202010011VC++: 140. C++의 연산자 동의어(operator synonyms), 대체 토큰 [1]
12423정성태11/22/202010978.NET Framework: 974. C# 9.0 - (16) 제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)파일 다운로드1
12422정성태11/21/20208773.NET Framework: 973. .NET 5, .NET Framework에서만 허용하는 UnmanagedCallersOnly 사용예파일 다운로드1
12421정성태11/19/20208514.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/20207708오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
12419정성태11/19/20208903VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202010997오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/20208377오류 유형: 682. Visual C++ - warning LNK4099: PDB '...pdb' was not found with '...lib(pch.obj)' or at '...pdb'; linking object as if no debug info
12416정성태11/19/20209662오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/20209685.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202010758VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202010438.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202012721.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/20209679오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/20209651디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202011046.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202022318도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202011330.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202012884.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202010393.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202010885.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202010945.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202011526.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...