重定向cpp中的stdout输出

时间:2012-06-24 10:38:00

标签: c++ windows redirect stdout

我几天来一直在寻找关于这个问题的答案,我希望你们能够帮助我。 (我搜索并找到了一些解决方案,但每个解决方案都有自己的问题......)。

这是事情: 我正在编写一个自动化工作,它负责启动我的同事编写的代码的外部“.exe”文件。当他们写的那些程序发给客户时,我不允许对他们的代码进行任何修改。这些程序一旦启动,就会等待特定的击键,并在收到合法的击键时打印一条消息。

我的目标是: 要编写一个执行外部程序的程序,发送它的击键,并从它们的标准输出接收输出。 到目前为止,我已经能够从我的程序运行程序(使用ShellExecute),并模拟某种类型的键盘监听器(使用SendMessage)到另一个程序。我可以看到它的工作原理 - 我可以在测试程序的控制台中看到输出。

我正在尝试实时获取测试程序shell上打印的消息(并在程序终止时获取大量数据),以便在发生时对其进行分析。

我尝试过的那些:

  • 使用内联输出重定向编写外部批处理文件到文本文件。
  • 使用freopen。
  • 在执行“ShellExecute”时重定向输出。

1 个答案:

答案 0 :(得分:0)

您使用stdin,stdout和stderr的句柄。使用CreateProcess函数创建进程以获取该句柄。 示例代码 - 对于您的案例不完整,但是如何执行该示例:

#include <windows.h>
#include <stdio.h>
#include <tchar.h>

    /*for test.exe
#include <iostream>
#include <string> */

void _tmain( int argc, TCHAR *argv[] )
{
    /*for test.exe
    std::cout << "test output" << std::endl;
    for (;;)
    {
        std::string line;
        std::getline(std::cin, line);
        std::cout << "line: " << line << std::endl;
    }
    return;*/
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    // Start the child process. 
    if( !CreateProcess( NULL,   // No module name (use command line)
        "test.exe",        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory 
        &si,            // Pointer to STARTUPINFO structure
        &pi )           // Pointer to PROCESS_INFORMATION structure
    ) 
    {
        printf( "CreateProcess failed (%d)\n", GetLastError() );
        return;
    }

   /*     HANDLE  hStdInput;
    HANDLE  hStdOutput;
    HANDLE  hStdError;*/
    HANDLE me_hStdInput = GetStdHandle(STD_INPUT_HANDLE);
    HANDLE me_hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    HANDLE proc_hStdInput = si.hStdInput;
    HANDLE proc_hStdOutput = si.hStdOutput;

                char buff[64];
                DWORD chars;
    while (!ReadConsole(me_hStdInput, buff, sizeof(buff), &chars, NULL))
    {
                    for (DWORD written = 0, writtenThisTime; written < chars; written += writtenThisTime)                   
                        if (!WriteConsole(proc_hStdOutput, buff + written, chars - written, &writtenThisTime, NULL))
                        {
                            //handle error - TODO
                        }
                }
                //possibly handle error for ReadConsole - TODO  


    // Wait until child process exits.
    //WaitForSingleObject( pi.hProcess, INFINITE );

    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}
相关问题