Jabberwocky
Jabberwocky

Reputation: 50775

Unable to redirect standard output using CreateProcess

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:

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

Upvotes: 3

Views: 1009

Answers (1)

RbMm
RbMm

Reputation: 33706

your hfile is not inheritable - you need use SECURITY_ATTRIBUTES in call CreateFile

SECURITY_ATTRIBUTES sa = { sizeof(sa), 0, TRUE };
HANDLE hfile = CreateFile("output.txt", GENERIC_WRITE, 0, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

Upvotes: 6

Related Questions