简体   繁体   English

fork()后管道的行为

[英]Behavior of a pipe after a fork()

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. 在UNIX环境中阅读高级编程中的管道时,我注意到在fork之后,父级可以close()管道的读取端,并且它不会关闭子级的读取端。 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. 我的意思是,在fork之前,管道读取文件描述符的保留计数为1,并且在fork 2之后。当父级关闭其读取侧时,fd变为1并且为子级保持打开状态。 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() : 正如人们可以在关于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() . fork()调用中,子进程获得每个文件描述符的独立副本,每个文件描述符的行为与dup()创建的一样。 A close() only closes the specific file descriptor that was passed - so for example if you do n2 = dup(n); close(n); close()只关闭传递的特定文件描述符 - 例如,如果你做n2 = dup(n); close(n); 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() . n所指的文件(管道,套接字,设备......)仍然是打开的 - 这同样适用于由fork()复制的文件描述符。

Yes, a fork duplicates all open file descriptors. 是的,fork复制了所有打开的文件描述符。

So for a typical pipe, a 2 slot array (int fd[2]), fd[0] is the same for the parent and child, and so is fd[1]. 因此对于典型的管道,2槽阵列(int fd [2]),fd [0]对于父和子是相同的,因此fd [1]。

You can create a pipe without forking at all, and read/write to yourself by using fd[0] and fd[1] in one process. 您可以创建一个完全没有分叉的管道,并在一个进程中使用fd [0]和fd [1]来自我读/写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM