When reading about pipes in Advanced Programming in the UNIX Environment, I noticed that after a fork the parent can close()
the read end of a pipe and it doesn't close the read end for the child. When a process forks, does its file descriptors get retained?
What I mean by this is that before the fork the pipe read file descriptor had a retain count of 1, and after the fork 2. When the parent closed its read side the fd went to 1 and is kept open for the child. Is this essentially what is happening? Does this behavior also occur for regular file descriptors?
As one can read on the man page about fork():
The child process shall have its own copy of the parent's file descriptors. Each of the child's file descriptors shall refer to the same open file description with the corresponding file descriptor of the parent.
So yes, the child have exact copy of parent's file descriptors and that refers to all of them, including open files.
The answer is yes, and yes (the same applies to all file descriptors, including things like sockets).
In a fork()
call, the child gets its own seperate copy of each file descriptor, that each act like they had been created by dup()
. A close()
only closes the specific file descriptor that was passed - so for example if you do n2 = dup(n); close(n);
, the file (pipe, socket, device...) that n
was referring to remains open - the same applies to file descriptors duplicated by a fork()
.
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