I have two executables – parent process and it’s child process, running in a long mode (for example server etc). All I need is to redirect child’s stdout and stderr to parent’s process and write them to file or print to tty, don’t matter now.
This is pretty straightforward task if we talking about simple child, but with long-running child with partial outputting it is a problem.
For example let’s look at popular solution with usage of pipe (error checking and other non-important parts omitted):
parent.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
int link[2];
pid_t pid;
char str[4096];
pipe(link);
pid = fork();
if (pid == 0) {
dup2(link[1], STDOUT_FILENO);
close(link[0]);
execl("/path_to_bin/fast_child", "fast_child", (char *)0);
}
else
{
close(link[1]);
read(link[0], str, sizeof(str));
printf("Pipe contents: %s\n", str);
wait(NULL);
}
return 0;
}
fast_child.c
#include <stdio.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
printf("I'm fast child\n");
return 0;
}
Using this type of child process in excellent and non-problematic way to get str(out|err) in parent, but using this code as child cause problems of output disappearing in parent:
slow_child.c
#include <stdio.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
for (;;)
{
printf("I'm slow child\n");
sleep(1);
}
return 0;
}
I’m thinking about socket usage as problem solving solution but I’m sure that this is not so efficient way and Unix provides better tools to do this (as usual 🙂
Thank you.
You need to flush your output from the child every now and then or the parent task won’t see anything. use
fflush(stdout)at appropriate points. Or you could switch off the buffering on stdout, but that might have a performance impact on your child, as it will do a system call on each character written.