fork() 之后管道的行为

发布于 2024-08-24 15:29:43 字数 231 浏览 9 评论 0原文

在阅读《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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

铁憨憨 2024-08-31 15:29:43

正如人们可以在手册页上读到的有关 fork() 的内容:

子进程应拥有自己的父进程文件副本
描述符。每个孩子的档案
描述符应引用相同的
打开文件描述
对应的文件描述符
父级。

所以是的,孩子拥有父母文件描述符的精确副本,并且引用了所有这些文件描述符,包括打开的文件。

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.

自找没趣 2024-08-31 15:29:43

答案是肯定的(这同样适用于所有文件描述符,包括套接字之类的东西)。

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

我的痛♀有谁懂 2024-08-31 15:29:43

是的,分叉会复制所有打开的文件描述符。

因此,对于一个典型的管道,一个 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文