I am not very sure how to create a pipe between two child processes. This is the way I did it:
pipe(&fd[0]); //Create a pipe
proc1 = fork();
//Child process 1
if (proc1 == 0)
{
close(fd[0]); //process1 doenst need to read from pipe
close(STD_INPUT); //prepare for output
dup(fd[1]); //Standard output = fd[1]
close(fd[1]);
execvp(parameter[0], parameter); //Execute the process
}
else
{
proc2 = fork();
if (proc2 == 0)
{
close(fd[1]);
close(STD_OUTPUT);
dup(fd[0]);
close(fd[0]);
execvp(parameter2[0], parameter2);
}
//Parent process
else
{
waitpid(-1, &status, 0); //Wait for the child to be done
}
}
I am trying to redirect the output of one child process to another, but I think I am making a mistake with the pipe in the second child process because when I run the program with the 2nd child process I get incorrect results (like a simple execution like "ls" is executed improperly), however, if I remove the second child process, the program runs fine (not including pipe, just simple fork: ls, ls -l, ps, etc.).
The best answer I can give is Beej's Guide to Unix IPC.
(Peek at section 4.3, where he gives a very similar example to the question you asked...)
In the child process 1 setup,
close(STD_INPUT); dup(fd[1]);
will duplicatefd[1]
to the lowest available descriptor, which is 0 (STD_INPUT
) rather than 1 (STD_OUTPUT
). Don't you want to closeSTD_OUTPUT
instead? Also, I'd recommenddup2(fd[1], STD_OUTPUT)
in place of this sequence; it will do what you want and is more clear anyway.Likewise child process 2 uses
STD_OUTPUT
where you probably wantSTD_INPUT
.