0

我有一个 MFC 应用程序,它通过CreateProcess函数向 cmd 发送命令。我想将标准输出放入日志文件。代码是这样的

    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);
    }

    }

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

4

1 回答 1

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 文档的 STARTF_USESTDHANDLES 部分,有很多信息。

顺便说一句,您还应该添加

CloseProcess(piProcessInfo.hProcess)

在末尾。

于 2013-08-30T13:08:54.707 回答