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).
Best Answer
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.
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.
However, POSIX (to which *nix systems largely or completely conform), stipulates that
read()
andwrite()
functions from the C API (which map to system calls) are "atomic with respect to each other [...] when they operate on regular files or symbolic links". The GNU C manually also provisionally promises this with regard to pipes (note the defaultPIPE_BUF
, which is part of the proviso, is 64 kiB). This means that calls in other languages/tools, such as use ofecho
orcat
, should be included in that contract, so if two indepenedent process try to write "hello" and "world" simultaneously to the same pipe, what will come out the other end is either "helloworld" or "worldhello", and never something like "hweolrllod".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.