Yola
Yola

Reputation: 19063

How to redirect std::cout and printf in windows

i have created program based on this article Creating a Child Process with Redirected Input and Output, but it doesn't work std::cout and printf, so from program like this i got ony "Hello, momma" string and nothing came from cout and printf parts:

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

Q: How can i intercept cout and printf? I have no access to source code of child program, i just need to intercept its output.


This is the output if run only child process:

Hello, momma - iostream version

Hello, momma - stdio versionHello, momma

so, as you can see, all three versions are printed.


As requested code of parent program:

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

Upvotes: 3

Views: 1398

Answers (1)

Ed Heal
Ed Heal

Reputation: 60037

You need to flush the buffers.

i.e.

cout << flush;
fflush(stdout);

before the return 0;

Upvotes: 1

Related Questions