gpt4 book ai didi

C: dup 和 close-on-exec

转载 作者:太空狗 更新时间:2023-10-29 15:06:51 26 4
gpt4 key购买 nike

在一本关于 C 编程的(德文)书中(Linux-UNIX-Programmierung,Jürgen Wolf 着)我找到了一个陈述,翻译成英文如下(句子由我编号):

In some cases it can be necessary that you need to duplicate a file descriptor [1]. An example for this would be, if a parent process wants to exchange data with a child process and the child process is overlaid by a new process through the use of exec*() [2]. In such a case, without dup() or dup2(), the close-on-exec flag would be set [3]. When this flag is set, all file descriptors become invalid (since being overlaid by the new process) - that is, they are not present anymore [4]. The communication between the parent and child process would thus be stopped [5]. If on the other hand you duplicate the file descriptor with dup() or dup2(), then the close-on-exec flag is deleted, and the newly overlaid process can use this file descriptor to communicate [6].

我认为上述段落包含若干误导性陈述甚至错误。

在句子 [3] 中,我不明白为什么不使用 dup()dup2() close-on-exec flag 会被设置?

最佳答案

建议是错误的。 Close-on-exec 仅在您的程序明确要求在执行时关闭的文件描述符上设置。

您可能选择使用 dup2 的原因可能是:

  • 要执行的进程期望它的 I/O 通过特定的文件描述符(通常是 0、1 和 2,分别对应于标准输入、输出和错误流),或者
  • 该进程将关闭一些文件描述符,无论出于何种原因,您需要此 fd 超出要关闭的范围。

描述也有点误导——它只是新描述符(即 dup()dup2() 的返回值)具有 close-on-exec未设置。原fd的close-on-exec状态不变。

关于C: dup 和 close-on-exec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41049765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com