fork() 之后管道的行为
在阅读《UNIX 环境中的高级编程》中有关管道的内容时,我注意到在分叉之后,父级可以 close()
管道的读取端,但它不会关闭子级的读取端。当进程分叉时,它的文件描述符会被保留吗?
我的意思是,在 fork 之前,管道读取文件描述符的保留计数为 1,而在 fork 之后为 2。当父进程关闭其读取端时,fd 变为 1 并为子进程保持打开状态。这本质上是正在发生的事情吗?常规文件描述符是否也会出现此行为?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如人们可以在手册页上读到的有关 fork() 的内容:
所以是的,孩子拥有父母文件描述符的精确副本,并且引用了所有这些文件描述符,包括打开的文件。
As one can read on the man page about fork():
So yes, the child have exact copy of parent's file descriptors and that refers to all of them, including open files.
答案是肯定的(这同样适用于所有文件描述符,包括套接字之类的东西)。
在
fork()
调用中,子进程获得每个文件描述符的自己单独的副本,每个文件描述符的行为就像它们是由dup()
创建的一样。close()
仅关闭传递的特定文件描述符 - 例如,如果您执行n2 = dup(n); close(n);
,n
引用的文件(管道、套接字、设备...)保持打开状态 - 这同样适用于由fork 复制的文件描述符()
。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 bydup()
. Aclose()
only closes the specific file descriptor that was passed - so for example if you don2 = dup(n); close(n);
, the file (pipe, socket, device...) thatn
was referring to remains open - the same applies to file descriptors duplicated by afork()
.是的,分叉会复制所有打开的文件描述符。
因此,对于一个典型的管道,一个 2 个槽数组(int fd[2]),父级和子级的 fd[0] 是相同的,fd[1] 也是如此。
您可以创建一个管道而无需分叉,并通过在一个进程中使用 fd[0] 和 fd[1] 来读取/写入自己。
Yes, a fork duplicates all open file descriptors.
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].
You can create a pipe without forking at all, and read/write to yourself by using fd[0] and fd[1] in one process.