Don't fork recursively. Making B a subprocess of A is not a good idea. For example, if B calls setsid
to run in its own session, it would take the unrelated A with it. If B dies, A would get a SIGCHILD, not you. In particular, you would not be able to obtain the return status of B.
Here's a sketch of the code to fork n children on a series of pipes. Warning: I typed the code directly into my browser; there are probably many typos, and I omitted all error checks.
char *executables[n];
char *args[n];
int pipes[2*n+2]; /* child i reads from */
int child_pids[n];
int ret; /*Error checking omitted; abort if ret ever becomes negative*/
ret = pipe(pipes);
for (i = 0; i < n; i++) {
ret = pipe(pipes + 2 * i + 2);
ret = fork();
if (ret == 0) {
/* Code of child i */
close(pipes[2*i+1]);
close(pipes[2*i+2]);
dup2(pipes[2*i], 0);
dup2(pipes[2*i+3], 1);
ret = execv(executables[i], args[i]);
}
close(pipes[2*i]);
close(pipes[2*i+3]);
child_pids[i] = ret;
}
/* interact with the subprocesses, then call wait or waitpid as needed */