I am trying to understand how pipes work . This code snippet is from some website .
So my understanding of the program goes like this :
When we do pipe(fd)
then fd[0]=3
and fd[0]=4
( assuming only 0
,1
& 2
are open till now ) . Now we fork the parent and then if a child is not created then we have error and it exits .
But if it child is created successfully , are the file descriptors copied to the child , I mean is fd[0]=3
and fd[1]=4
for the child process also ? fd[0]
and fd[1]
are file handles to which files ( we have not specifically specified ) ?
Let us suppose that we want child to read from parent then , parent should close fd[0]
and child should close fd[1]
but why ? What will happen if we do not close them ?
And I didn't understand On a technical note, the EOF will never be returned if the unnecessary ends of the pipe are not explicitly closed.
.
If the parent wants to receive data from the child, it should close fd1, and the child should close fd0. If the parent wants to send data to the child, it should close fd0, and the child should close fd1. Since descriptors are shared between the parent and child, we should always be sure to close the end of pipe we aren't concerned with. On a technical note, the EOF will never be returned if the unnecessary ends of the pipe are not explicitly closed.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
main()
{
int fd[2];
pid_t childpid;
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
}
.
.
}