我已经基于本文Creating a Child Process with Redirected Input and Output创建了程序,但是它不能在std::cout和printf上运行,因此从这样的程序中我只能看到“Hello,momma”字符串,而cout和printf的任何部分都没有:
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
const char *buffer = "Hello, momma";
std::cout << buffer << " - iostream version\n";
printf("%s - stdio version", buffer);
DWORD dwWritten = 0;
WriteFile(hStdOut, buffer, strlen(buffer), &dwWritten, NULL);
return 0;
}
问:如何截获cout和printf? 我无法访问来访问子程序的源代码,我只需要截取其输出即可。如果仅运行子进程,则为以下输出:
因此,如您所见,所有三个版本均已打印。
根据父程序的要求代码:
void RedirectIO(HANDLE &hRead, HANDLE &hWrite)
{
SECURITY_ATTRIBUTES attr;
ZeroMemory(&attr, sizeof(attr));
attr.nLength = sizeof(attr);
attr.bInheritHandle = true;
CreatePipe(&hRead, &hWrite, &attr, 0);
SetHandleInformation(hRead, HANDLE_FLAG_INHERIT, 0);
}
bool CreateChild(std::string CommandLine, DWORD WaitTime, HANDLE hInRead, HANDLE hOutWrite)
{
STARTUPINFO SI;
PROCESS_INFORMATION PI;
ZeroMemory(&SI, sizeof(SI));
ZeroMemory(&PI, sizeof(PI));
SI.cb = sizeof(SI);
SI.hStdError = hOutWrite;
SI.hStdInput = hInRead;
SI.hStdOutput = hOutWrite;
SI.dwFlags |= STARTF_USESTDHANDLES;
bool success = CreateProcess(0, const_cast<char*>(CommandLine.c_str()), 0, 0, true, NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, 0, 0, &SI,&PI);
if (success)
{
WaitForSingleObject(PI.hProcess, WaitTime);
CloseHandle(PI.hProcess);
CloseHandle(PI.hThread);
}
return success;
}
int main()
{
HANDLE hRead = nullptr;
HANDLE hWrite = nullptr;
RedirectIO(hRead, hWrite);
CreateChild("stdouterrin.exe", INFINITE, nullptr, hWrite);
DWORD ReadCount = 0;
char Buffer[1024] = {0};
std::string data = std::string();
while(true)
{
if (!ReadFile(hRead, Buffer, sizeof(Buffer) / sizeof(char), &ReadCount, 0))
break;
if (!ReadCount) break;
Buffer[ReadCount] = '\0';
data.append(&Buffer[0], ReadCount);
std::cout<<"Read From Child:\n\n"<<data.c_str()<<"\n";
}
return 0;
}
最佳答案
您需要刷新缓冲区。
IE。
cout << flush;
fflush(stdout);
在
return 0;
之前