I'm maintaining an MFC program and I'm launching a simple Win32 console program (just a "Hello World" program, source below) with CreateProcess and I'm unable to redirect the standard output of that program to a file.
This is the launching code, don't bother about the Fatal function, it just
displays a message and aborts the program, this is only test code.
HANDLE hfile = CreateFile("output.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hfile == INVALID_HANDLE_VALUE)
{
Fatal("Fatal error: CreateFile");
}
static const char TestText[] = "Test\r\n";
DWORD written;
if (!WriteFile(hfile, "Test\r\n", sizeof(TestText) - 1, &written, NULL))
{
Fatal("Fatal error: CreateProcess");
}
STARTUPINFO startupinfo = {0};
startupinfo.cb = sizeof(STARTUPINFO);
startupinfo.lpTitle = "Some Title";
startupinfo.dwFlags = STARTF_USESTDHANDLES;
startupinfo.hStdOutput = hfile;
PROCESS_INFORMATION processInfo;
if (!CreateProcess("S:\\Git\\TestRedirect\\TestConsole1\\Debug\\TestConsole1.exe", "cmdline", NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &startupinfo, &processInfo))
{
Fatal("Fatal error: CreateProcess");
}
if (WaitForSingleObject(processInfo.hProcess, 10000) != WAIT_OBJECT_0)
{
Fatal("Fatal error: WaitForSingleObject");
}
if (!CloseHandle(hfile))
{
Fatal("Fatal error: CloseHandle");
}
It almost works as expected:
- it opens "output.txt"
- it writes "Test\r\n" into "output.txt"
- it launches TestConsole1.exe
- the console window of TestConsole1.exe does not display "Hello Word", which is expected because the standard output is supposed to be redirected into "output.txt"
WaitForSingleObjectwaits for TestConsole1.exe to be completedCloseHandlecloses "output.txt"
Now I expect "output.txt" to contain this:
Test
Hello World!
but actually it's content is
Test
Source code of TestConsole1.exe:
#include <stdio.h>
#include <windows.h>
int main(int argc, char* argv[])
{
printf("Hello World!\n");
Sleep(2000); // wait 2 seconds so I can see what happens
return 0;
}