0

I am now learning about the process programming on C++, and I have a question now about the fork() and pipe().

I need to run two programs in parallel, and program A's standard output connected to B's standard input, and B's standard output connected to A's standard input.

For this particular question, am I supposed to have 2 pipes? How can I run them recursively? Could any of you can provide me an example? Thank you very much.

EDIT: I got something like that but it didn't work.

int pipe1[2];
int pipe2[2];
pipe(pipe1);
pipe(pipe2);

pid = fork();
if (pid == 0) {
    dup2(pipe1[0], 0);
    close(pipe1[1]);
    close(pipe1[0]);

    dup2(pipe2[1], 1);
    close(pipe2[0]);
    close(pipe2[1]);

    execvp(A[0],A);
} else {
    dup2(pipe2[0], 0);
    close(pipe2[0]);
    close(pipe2[1]);

    dup2(pipe1[1], 1);
    close(pipe1[1]);
    close(pipe1[0]);

    execvp(B[0],B);
}
RobinXu
  • 23
  • 6
  • Hint: some fork, exec, pipe and dup work is on the horizon. (not necessarily in that order). – WhozCraig Dec 06 '19 at 06:54
  • First step should be reading the manual page of [fork](http://man7.org/linux/man-pages/man2/fork.2.html) and [pipe](http://man7.org/linux/man-pages/man2/pipe.2.html). Then there is a good example here [fork() and pipes() in c/c++](https://stackoverflow.com/questions/4812891/fork-and-pipes-in-c) – Achal Dec 06 '19 at 06:57
  • @WhozCraig Thanks. But I cannot figure out how many pipes should I use. – RobinXu Dec 06 '19 at 07:08
  • @Achal Thanks. But I cannot figure out how many pipes should I use. – RobinXu Dec 06 '19 at 07:09
  • You'll need two descriptor pairs. Remember, `pipe()` makes a pair of descriptors (a read end, and a write end), so there will be two `pipe()` calls near inception of your program. – WhozCraig Dec 06 '19 at 07:11
  • @WhozCraig I got something, but it doesn't work. – RobinXu Dec 06 '19 at 07:52

0 Answers0