r/C_Programming • • Feb 16 '23

Question WinApi ChildProcess handling Problem

Hey,I'm trying to create a little test program using the WinApi that launches a child process and reads/writes its stdout/stdin (similar like Gos os/exec package) but I can't find my error.

Here is the code:

#include <stdio.h>
#include <stdlib.h>

#include <Windows.h>
#include <stdbool.h>

// exit with the GetLastError error message
void ErrorExit()
{
	char err[1024];
	FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
				   NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), err, sizeof(err), NULL);
	printf("Error: %s", err);
	exit(1);
}

/*
	This Program launches the given program (argv[1])
	and writes something to its stdin, then reads its stdout/stderr
	and waits for it to finish

	reference: https://learn.microsoft.com/en-us/windows/win32/procthread/creating-a-child-process-with-redirected-input-and-output
*/
int main(int argc, char *argv[])
{
	if (argc < 2)
	{
		printf("no args given\n");
		return 1;
	}

	// prepare the command line arguments for the child process
	char testArgs[1024];
	strcpy(testArgs, argv[1]);
	strcat(testArgs, " a_Argument another_Argument");

	SECURITY_ATTRIBUTES saAttr;
	saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
	saAttr.bInheritHandle = true;
	saAttr.lpSecurityDescriptor = NULL;

	// the pipe read/write handles for the stdin/stdout pipes that are given to the child process
	HANDLE hStdoutPipe_rd; // read end for the stdout pipe (parent process uses this to read the childs stdout)
	HANDLE hStdoutPipe_wr; // write end for the stdout pipe (child process uses this as its stdout)
	HANDLE hStdinPipe_rd;  // read end for the stdin pipe (child process uses this as its stdin)
	HANDLE hStdinPipe_wr;  // write end for the stdin pipe (parent process uses this to write to the childs stdin)

	// create the stdout/stdin pipes
	printf("creating pipes\n");
	if (!CreatePipe(&hStdoutPipe_rd, &hStdoutPipe_wr, &saAttr, 0)) // create the stdout pipe
		ErrorExit();
	if (!SetHandleInformation(hStdoutPipe_rd, HANDLE_FLAG_INHERIT, 0)) // don't know why we need this
		ErrorExit();
	if (!CreatePipe(&hStdinPipe_rd, &hStdinPipe_wr, &saAttr, 0)) // create the stdin pipe
		ErrorExit();
	if (!SetHandleInformation(hStdinPipe_wr, HANDLE_FLAG_INHERIT, 0)) // don't know why we need this
		ErrorExit();

	// parameter for CreateProcess
	STARTUPINFOA si = {sizeof(si)};		// zero-memory
	si.cb = sizeof(STARTUPINFOA);		// was like this in the docs, whatever
	si.hStdOutput = hStdoutPipe_wr;		// the child uses the write end of the stdout pipe as its stdout/stderr
	si.hStdError = hStdoutPipe_wr;		// the child uses the write end of the stdout pipe as its stdout/stderr
	si.hStdInput = hStdinPipe_rd;		// the child uses the read end of the stdin pipe as its stdin
	si.dwFlags |= STARTF_USESTDHANDLES; // tell CreateProcess to use the given handles as stdin/stdout/stderr

	PROCESS_INFORMATION pi; // output parameter for CreateProcess

	// create the process
	printf("creating process\n");
	if (!CreateProcessA(argv[1], testArgs, NULL, NULL, false, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi))
		ErrorExit();

	// why close the handles before the child process is finished,
	// I thought the child process needs them (the docs do this)
	// if I uncomment these, I also get and error when trying to write to hStdinPipe_wr
	// saying "pipe is getting closed"
	// so I really don't know why the docs do this or if their example even works
	// CloseHandle(hStdoutPipe_wr);
	// CloseHandle(hStdinPipe_rd);

	const char *input = "hey little one";

	printf("writing to processes stdin\n");
	{
		// write input to the child processes stdin
		DWORD dwWritten;
		if (!WriteFile(hStdinPipe_wr, input, strlen(input), &dwWritten, NULL))
			ErrorExit();
	}

	// read the child processes in chunks
	printf("reading processes stdout:\n");
	while (true)
	{
		// 9-byte chunks plus 0-terminator to print it
		// (only 9 byte to check that it is read continuasly)
		char buff[10];
		buff[sizeof(buff) - 1] = '\0';
		DWORD dwRead;

		printf("ReadFile");
		// this call never returns even though the child process is already done
		// why is that?
		// also, how is ReadFile supposed to know when there's nothing more to read?
		if (!ReadFile(hStdoutPipe_rd, buff, sizeof(buff) - 1, &dwRead, NULL) || dwRead == 0)
			break;
		printf("read file");

		// print what was read
		buff[dwRead] = '\0';
		printf("%s", buff);
	}

	// I thought, maybe the process is still running even though there's no more output
	// so wait for it to exit just to be sure
	printf("\nwaiting for process to exit\n");
	WaitForSingleObject(pi.hProcess, INFINITE);

	// get the exit code of the process and print it
	DWORD exit_code;
	GetExitCodeProcess(pi.hProcess, &exit_code);
	printf("child exited with code %d\n", exit_code);

	// close all the remaining handles

	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);

	CloseHandle(hStdoutPipe_rd);
	CloseHandle(hStdinPipe_wr);

	return 0;
}

Here is the program used for the child process:

#include <stdio.h>

int main(int argc, char *argv[])
{
	printf("test_process started with these arguments:\n");
	for (int i = 0; i < argc; i++)
	{
		printf("%s\n", argv[i]);
	}
	printf("now reading input:\n");
	char c;
	while ((c = getchar()) != EOF)
	{
		printf("%c", c);
	}
	return 0;
}

I compile both and launch them

./main.exe test_process.exe

the comments in the main program should explain what I'm trying to do.I think the real problem is that I don't really understand pipes and/or child processes really good yet, but I also don't know where to research it properly.

It works until the ReadFile call trying to read the child processes stdout, but this call just never returns and I don't know why.
I confirmed that the child process finishes by creating some files in it.
It runs until the end, but the parent process still reads no stdout.

I also found this stackoverflow post but it didn't really help me.

Thanks for any help to get this to work.

5 Upvotes

7 comments sorted by

View all comments

Show parent comment

3

u/bafto14 Feb 16 '23

Thanks! Calling SetHandleInformation with a 0 as last parameteter fixed it as you said.

I'm not 100% sure why though, because I thought I wanted to inherit those handles? Either I don't understand what inheriting handles means or I don't understand what it means to set that bit twice (with SECURITY_ATTRIBUTES and SetHandleInformation) but well whatever, I will look into it.

Thank you for all the help!