Pipe behavior after plug ()

When reading about works in advanced programming on UNIX, I noticed that after the fork, the parent can close() read the end of the pipe, and it does not close the end of the read for the child. When the fork process, its file descriptors are saved?

What I mean is that before the fork, the channel file descriptor has a storage counter of 1 and after fork 2. When the parent closed his read side, fd went to 1 and remains open for the child. This, in fact, , what's happening? Does this also happen for regular file descriptors?

+7
c unix pipe fork
source share
3 answers

As you can read on the man page about fork () :

The child process must have its own copy of the parent file descriptors. Each of the child file descriptors must reference the same open file description using the corresponding file descriptor parent.

So yes, the child has an exact copy of the descriptors of the parent files, and this applies to all of them, including open files.

+5
source share

The answer is yes and yes (the same applies to all file descriptors, including things like sockets).

In the fork() call, the child gets its own separate copy of each file descriptor, each of which acts as if they were created using dup() . A close() closes only the specific file descriptor that was transferred - for example, if you do n2 = dup(n); close(n); n2 = dup(n); close(n); , the file (pipe, socket, device ...) that n had in mind remains open - the same applies to file descriptors duplicated with fork() .

+2
source share

Yes, the fork duplicates all open file descriptors.

So, for a typical channel, an array of 2 slots (int fd [2]), fd [0] is the same for the parent and child, as well as fd [1].

You can create a channel without markup at all and read / write to yourself using fd [0] and fd [1] in one process.

+1
source share

All Articles