8

When a child is forked then it inherits parent's file descriptors, if child closes the file descriptor what will happen ? If child starts writing what shall happen to the file at the parent's end ? Who manages these inconsistencies , kernel or user ?

when a process calls the close function to close a particular open file through file descriptor. In the file table of the process, the reference count is decremented by one. But since parent and child are both holding the same file, the reference count is 2 and after close it reduces to 1. Since it is not zero the process still continue to use file without any problem.

See Terrence Chan UNIX system programming,(Unix kernel support for Files).

  • Okay, never mind that last comment ;) In the man pages for open() and fork() there is a distinction between a file descript-or and a file descipt-ion -- the former refers to the later, and although the descriptors in a fork are copies, they refer to the same description. However, when tested it is obvious this does not mean closing the child's handle closes the parents handle. I think it might make a subtle difference to the interleaving of data when both handles write -- but that is indeterminate anyway, so exactly how it happens is not so important. – goldilocks Sep 17 '13 at 14:44
20

When a child is forked then it inherits parent's file descriptors, if child closes the file descriptor what will happen ?

It inherits a copy of the file descriptor. So closing the descriptor in the child will close it for the child, but not the parent, and vice versa.

If child starts writing what shall happen to the file at the parent's end ? Who manages these inconsistencies , kernel or user ?

It's exactly (as in, exactly literally) the same as two processes writing to the same file. The kernel schedules the processes independently, so you will likely get interleaved data in the file.

when a process call close function to close a particular open file through file descriptor.The file table of process decrement the reference count by one.But since parent and child both are holding the same file(there refrence count is 2 and after close it reduces to 1)since it is not zero so process still continue to use file without any problem.

There are TWO processes, the parent and the child. There is no "reference count" common to both of them. They are independent. WRT what happens when one of them closes a file descriptor, see the answer to the first question.

1

Whenever fork() makes a new child, the file descriptors are not retained at all - they are changed.

Although the file will be a duplicate, it will have a different file descriptor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.