如何在Windows中重定向std :: cout和printf

时间:2014-01-17 16:54:10

标签: c++ windows

我已经基于这篇文章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? 我没有访问来查看子程序的源代码,我只需要截取它的输出。


这是仅运行子进程的输出:

  

您好,妈妈 - iostream版本

     

你好,妈妈 - stdio版你好,妈妈

所以,正如您所看到的,所有三个版本都已打印出来。


作为父程序的请求代码:

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

1 个答案:

答案 0 :(得分:1)

您需要刷新缓冲区。

cout << flush;
fflush(stdout);
return 0;

之前