If you do a fork() on a parent and create a child process, and then the child closes the fd inherited from the fork.
Would the file stay open in the parent, since they're independent? What about standard i/o or stderr?
File descriptors are generally unique to each process, but they can be shared by child processes created with a fork subroutine or copied by the fcntl, dup, and dup2 subroutines.
close() closes a file descriptor, so that it no longer refers to any file and may be reused.
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.
Yes, close your file descriptors and free all heap memory, even if you know that the OS will clean it up - that way, when you run valgrind or some similar tool, you don't get a lot of noise in the results, and you can easily recognize "legit" fd leaks.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With