I know how to do this in Linux, but I'm a bit lost when trying this with Win32... This is my best attempt so far, it compiles but the child process still prints to the terminal instead of the txt file.
The directory:
|__ parent.exe
|
|__ child.exe
|
|__ out.txt
The code:
STARTUPINFO si;
PROCESS_INFORMATION pi;
DWORD status ; // used to receive the exit status
SECURITY_ATTRIBUTES sa;
// fill the attributes with zeros
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
ZeroMemory(&sa, sizeof(sa));
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
HANDLE fh = CreateFile("./out.txt",
GENERIC_WRITE, // open for writing
TRUE, // sharing okay
&sa, // inherit OK
OPEN_EXISTING, // open existing file
FILE_ATTRIBUTE_NORMAL, // normal file
NULL);
si.hStdOutput = fh;
si.cb = sizeof(si);
CreateProcess(
"./child.exe",
NULL,
NULL,
NULL,
TRUE, // handles are inherited
0,
NULL,
NULL,
&si,
&pi
);
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(fh);
// other code for handling the child process
Not sure if relevant but it's compiled with gcc (mingw)
question from:
https://stackoverflow.com/questions/65866751/redirecting-the-output-of-a-child-process-to-local-txt-file-in-win32-api 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…