سؤال

I have a MFC application which send a command to cmd through CreateProcess function. I want to get the stdout into a log file. The code is like this

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

    }

but the code is not working properly . Only a blank file is created. What i am doing wrong ? Please help.

هل كانت مفيدة؟

المحلول

You forgot to speficy the STARTF_USESTDHANDLES flag in siStartupInfo.dwFlags.

Change

startupInfo.dwFlags = STARTF_USESHOWWINDOW  ;

to

startupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES ;

and change

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

to

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

I suggest you read the STARTF_USESTDHANDLES section of the STARTUPINFO documentation, there is plenty of information.

BTW you should also add

CloseProcess(piProcessInfo.hProcess)

at the end.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top