将命令行进程的Stdout重定向到文件

时间:2013-08-30 10:41:49

标签: mfc stdout createprocess

我有一个MFC应用程序,通过 CreateProcess 函数向cmd发送命令。我想将stdout放入日志文件中。代码就像这样

    void CMainFrame::OnCompile( CString cmd )
    {
    CWaitCursor cursor;

    SECURITY_ATTRIBUTES sec;
    ZeroMemory( &sec, sizeof(sec) );
    sec.nLength = sizeof(SECURITY_ATTRIBUTES);
    sec.lpSecurityDescriptor = NULL;    
    sec.bInheritHandle = TRUE;

    HANDLE hstdoutf = CreateFile("e:\\user_stdout.txt",GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,&sec,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);

    STARTUPINFO siStartupInfo;
    PROCESS_INFORMATION piProcessInfo;
    memset(&siStartupInfo, 0, sizeof(siStartupInfo));
    memset(&piProcessInfo, 0, sizeof(piProcessInfo));
    siStartupInfo.cb = sizeof(siStartupInfo);
    siStartupInfo.dwFlags = STARTF_USESHOWWINDOW  ;
    siStartupInfo.wShowWindow = SW_HIDE; 




    if (hstdoutf!=INVALID_HANDLE_VALUE) {
        siStartupInfo.hStdOutput=hstdoutf;
    }
    // Wait up to 100 seconds for the compilation process to finish
    if (!::CreateProcess(0, (char*)(cmd.GetString()), 0, 0, false,0, 0, 0,     
    &siStartupInfo, &piProcessInfo) ||
        (WaitForSingleObject(piProcessInfo.hProcess, 100000) != WAIT_OBJECT_0))
    {
        MessageBox("Fail to execute command","Test",MB_ICONERROR);
    }
    else
    {
        CloseHandle(hstdoutf);
    }

    }

但代码无法正常运行。仅创建一个空白文件。 我做错了什么?请帮忙。

1 个答案:

答案 0 :(得分:1)

您忘记在siStartupInfo.dwFlags中使用STARTF_USESTDHANDLES标志。

更改

startupInfo.dwFlags = STARTF_USESHOWWINDOW  ;

startupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES ;

并更改

CreateProcess(0, (char*)(cmd.GetString()), 0, 0, false, 0, 0, 0,
    &siStartupInfo, &piProcessInfo)

CreateProcess(0, (char*)(cmd.GetString()), 0, 0, true, 0, 0, 0,
    &siStartupInfo, &piProcessInfo)

我建议你阅读STARTUPINFO documentation的STARTF_USESTDHANDLES部分,有很多信息。

BTW你还应该添加

CloseProcess(piProcessInfo.hProcess)

最后。