Search code examples
linuxfileforkparent-childsystem-calls

Parent/child process close file descriptor


If you do a fork() on a parent and create a child process, and then the child closes the fd (file descriptor) inherited from the fork (parent).

Would the file stay open in the parent, since they're independent? What about standard i/o or stderr?


Solution

  • Regardless of whether a file descriptor represents a file or a device, and regardless of whether it was ever passed as a standard i/o descriptor to any process: if you close it in one process, the other process still has a valid descriptor.

    (This is pretty natural. Imagine for a moment that the descriptor would be interdependent with the descriptor in the other process. Then, if a child process unexpectedly crashed, the parent process would have difficulty to even log this fact, once the crash was detected. It could not log the fact through any previously open descriptor, because all forms of process exit involve closing of all open descriptors. Failure modes would therefore tend to spread across processes. In addition, even regular, error free I/O patterns through such hypothetical shared descriptors would abound in race conditions.)