在cpp中redirect标准输出

我几天前一直在寻找这个问题的答案,希望你们能帮助我。 (我已经search并find了一些解决scheme,但每个都有自己的问题…)。

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

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

我试图在testing程序的shell中实时地获取打印的消息(并在程序终止时获取大量数据),以便在出现问题时对其进行分析。

那些我试过的:

  • 使用内联输出redirect将外部batch file写入文本文件。
  • 使用freopen。
  • 在执行“ShellExecute”的同时redirect输出。

您使用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 ); }