I have two C programs and am trying to call some child program "child.c" inside of some parent program "parent.c", and capturing the output to stdout from child.c. How would I go about doing this?
I am using macOS.
Here's an example of what parent.c and child.c might look like
parent.c
while (1)
{
// call the child program
// capture the output from the child
if (child_output == some_condition)
{
break;
}
}
printf("Hello world!")
Simply use popen()
and create a stream object of type FILE *
which you can use with fread()
/fgets()
to get the output from the child program. Reading the manual page should be enough to get you started.
But here is an example
#include <stdio.h>
int
main(void)
{
FILE *pipe;
char line[256];
pipe = popen("ls", "r");
if (pipe != NULL) {
while (fgets(line, sizeof line, pipe) != NULL) {
fprintf(stdout, "%s", line);
}
pclose(pipe);
}
return 0;
}
Also, read the manual to get an idea of how this actually works.