c++ - Unable to redirect standard output using CreateProcess -


i'm maintaining mfc program , i'm launching simple win32 console program (just "hello world" program, source below) createprocess , i'm unable redirect standard output of program file.

this launching code, don't bother fatal function, displays message , aborts program, 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 works expected:

  • it opens "output.txt"
  • it writes "test\r\n" "output.txt"
  • it launches testconsole1.exe
  • the console window of testconsole1.exe not display "hello word", expected because standard output supposed redirected "output.txt"
  • waitforsingleobject waits testconsole1.exe completed
  • closehandle closes "output.txt"

now expect "output.txt" contain this:

test
hello world!

but 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 can see happens     return 0; } 

your hfile not inheritable - need use security_attributes in call createfile

security_attributes sa = { sizeof(sa), 0, true }; handle hfile = createfile("output.txt", generic_write, &sa, null, create_always, file_attribute_normal, null); 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -