Reputation: 19
I write the following code, and it seems to work well
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
char *msg1 = "parent->child";
char *msg2 = "child->parent";
int main(){
int fd[2];
char *byte = "pingpong";
char buf[20];
pipe(fd);
if(fork() == 0){
if(read(fd[0],buf,20) >0){
printf("%d: received ping\n",getpid());
printf("child buf -> %s\n",buf);
}
close(fd[0]);
write(fd[1],msg2,strlen(msg2)+1);
close(fd[1]);
exit(0);
}
else{
write(fd[1],msg1,strlen(msg1)+1);
close(fd[1]);
wait(0);
if(read(fd[0],buf,20) > 0){
printf("%d: received pong\n",getpid());
printf("parent buf -> %s\n",buf);
}
close(fd[0]);
}
exit(0);
}
giving the result answer
938: received ping
child buf -> parent->child
937: received pong
parent buf -> child->parent
but in "advanced programming in unix environment" I read this sentence:
If we read from a pipe whose write end has been closed, read returns 0 to indicate an end of file after all the data has been read. (Technically, we should say that this end of file is not generated until there are no more writers for the pipe.
how does the child process read from pipe ?
Upvotes: 0
Views: 70
Reputation: 126175
After the fork, you have two file descriptors open on each of the pipe, one in the parent and one in the child (so a total of FOUR descriptors -- child read, child write, parent read, parent write). The write end of the pipe will only be closed when both the child and parent close their write descriptors.
So the child does a read on the pipe and the parent does a write (the child will block until the parent runs if it runs first). Then the child does a write while the parent does a read (and now the parent will block until the child does the write). Only after the child does its write will it close the write end of the pipe.
Since both messages are less than PIPE_BUF in length, they'll be written "atomically" (won't get split and mixed with other messages), but that doesn't really matter as the child won't do its write until after it has done its read (which will block until after the parent's write), so there are no races here.
Upvotes: 0