Pipe() with fork() with recursion: File Descriptors handling

后端 未结 1 1476
闹比i
闹比i 2021-01-21 17:02

I have confusion regarding an existing question that was asked yesterday:
Recursive piping in Unix again.

I am re-posting the problematic code:

#incl         


        
相关标签:
1条回答
  • 2021-01-21 17:45

    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.

    0 讨论(0)
提交回复
热议问题