I have confusion regarding an existing question that was asked yesterday:
Recursive piping in Unix again.
I am re-posting the problematic code:
#incl
when we fork() a process, then the file descriptors are also duplicated. Hence the parent and child should have different file descriptors
file descriptor is a simple integer
. so when it is copied, it has same value so they point to same file.
So you can open a file in parent, and access it from child. Only problem that may occur is if the file is accessed from parent and child both, in that case it is not guaranteed from which position of the file it will access. To avoid this, it is recommended to close the fd in child and reopen.
As you have stated your attempt, I did the same for the said problem and find that this is happening for 4th command always. Also, dup2()
closes the file which it is duplicating. In the problem, fd[1]
and in_fd
was duplicated to the child's stdin
and stdout
. and fd[1]
and in_fd
was closed in that moment. There is no need to close them again.
Closing a already closed descriptor will cause error.
And as you do not know whether parent or child is going to execute first, if you close one file from child, and again close from parent, may cause problem, and this type of behavior is unpredictable.