C: dup 和 close-on-exec
C: dup and close-on-exec
在一本关于 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 标志会是设置?
建议是错误的。 Close-on-exec 仅在您的程序明确要求在执行时关闭的文件描述符上设置。
您可能选择使用 dup2
的原因可能是:
- 要执行的进程期望它的I/O通过特定的文件描述符(通常是0、1和2,分别对应标准输入、输出和错误流),或者
- 进程将关闭一些文件描述符,无论出于何种原因,您需要此 fd 超出要关闭的范围。
描述也有点误导——它只是新描述符(即来自 dup()
或 dup2()
的 return 值)未设置 close-on-exec。原fd的close-on-exec状态不变
在一本关于 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, withoutdup() 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 withdup() 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 标志会是设置?
建议是错误的。 Close-on-exec 仅在您的程序明确要求在执行时关闭的文件描述符上设置。
您可能选择使用 dup2
的原因可能是:
- 要执行的进程期望它的I/O通过特定的文件描述符(通常是0、1和2,分别对应标准输入、输出和错误流),或者
- 进程将关闭一些文件描述符,无论出于何种原因,您需要此 fd 超出要关闭的范围。
描述也有点误导——它只是新描述符(即来自 dup()
或 dup2()
的 return 值)未设置 close-on-exec。原fd的close-on-exec状态不变