In the code below, the process creates one child ( fork () ), and then the child replaces itself by calling exec () . stdout exec is written to pipe instead of shell. Then the parent process reads from the pipe what exec wrote with while (read (pipefd [0], buffer, sizeof (buffer))! = 0)
Can someone tell me how to do the same thing as described above, but with N number of child processes (which replace themselves with exec as above).
int pipefd[2];
pipe(pipefd);
if (fork() == 0)
{
close(pipefd[0]); // close reading end in the child
dup2(pipefd[1], 1); // send stdout to the pipe
dup2(pipefd[1], 2); // send stderr to the pipe
close(pipefd[1]); // this descriptor is no longer needed
exec(...);
}
else
{
// parent
char buffer[1024];
close(pipefd[1]); // close the write end of the pipe in the parent
while (read(pipefd[0], buffer, sizeof(buffer)) != 0)
{
}
}
source
share