简体   繁体   中英

Ring of two processes using a pipe

I have this example of pipe and dup use. It is supposed to create a ring of two processes connected by a pipe. Here is the code:

#include <unistd.h>

#define READ 0
#define WRITE 1

main (int argc, char *argv[]) {
 int fd[2];
 pipe(fd); //first call to pipe
 dup2(fd[READ],0);
 dup2(fd[WRITE],1);
 close(fd[READ]);
 close(fd[WRITE]);
 pipe(fd); //second call to pipe

 if (fork()==0) {
    dup2(fd[WRITE],1);
 } else
    dup2(fd[READ],0);

 close(fd[READ]);
 close(fd[WRITE]);
}

From "ring of two processes" I understand that the output of the process A is connected to the input of the process B, and the output of the process B is connected to the input of the process A.

After the first call of pipe, and the two succesive calls of dup2, I think the standard input and output were redirected to the input and output of my new pipe.

Then, it came the second call to pipe which confuses me, since I think it overwrites my previous fd values. At this point what is going on with the standard input and output?

Finally, the fork call:

does the child redirect the standard output to the pipe?

does the parent redirect the standard input to the pipe?

I can't see the ring here.

I hope I made myself clear, since I'm really confused.

Thank you very much!!

Ok, let's just pretend you've started this thing from a terminal. Then you have:

file 0 (stdin)  = terminal keyboard
file 1 (stdout) = terminal screen
file 2 (stderr) = terminal screen

Now you run pipe(fd) , and you have:

file 0-2 = as before
file 3 (fd[0]) = read end of pipe 1
file 4 (fd[1]) = write end of pipe 1

Now you run the first two dup2 s and the first two close s:

file 0 = read end of pipe 1
file 1 = write end of pipe 1
file 2 = still terminal screen
file 3-4 = now closed

Now you make a new pipe :

file 0-2 as before
file 3 (fd[0]) = read end of pipe 2
file 4 (fd[1]) = write end of pipe 2

And now you fork. In the child process you call dup2(fd[1],1) and close both fd s (your source isn't quite right here):

file 0: read end of pipe 1
file 1: write end of pipe 2
file 2: terminal screen
file 3-4: closed

In the parent process you call dup2(fd[0],0) , and again close both fd s giving it:

file 0: read end of pipe 2
file 1: write end of pipe 1
file 2: terminal screen
file 3-4: closed

So we have the parent process writing its stdout to pipe 1, which the child reads its stdin from. Similarly, we have the parent process reading its stdin from pipe 2, which the child is writing its stdout to. Ie, a ring of two processes.

I was always taught that this sort of arrangement was prone to deadlock. I don't know if that is true with more modern Unixes, but it is worth a mention.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM