Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of a pipe after a fork()

Tags:

c

fork

unix

pipe

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?

like image 736
Stephen Melvin Avatar asked Mar 11 '10 21:03

Stephen Melvin


2 Answers

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.

like image 93
pajton Avatar answered Oct 26 '22 14:10

pajton


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

like image 31
caf Avatar answered Oct 26 '22 15:10

caf