Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 inherited from the fork.

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

like image 420
CyberShot Avatar asked Apr 17 '12 20:04

CyberShot


People also ask

Do parent and child processes share file descriptors?

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.

How do I close file descriptor?

close() closes a file descriptor, so that it no longer refers to any file and may be reused.

What happens within a parent process when a child closes a file descriptor inherited across a fork?

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.

Do you have to close file descriptors?

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.


1 Answers

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.)

like image 187
Jirka Hanika Avatar answered Sep 24 '22 01:09

Jirka Hanika