[英]C: dup and close-on-exec
In a (German) book about C programming (Linux-UNIX-Programmierung, by Jürgen Wolf) I have found a statement, which translated to English would be as following (sentences numbered by me): 在一本关于C编程的(德语)书中(Linux-UNIX-Programmierung,由JürgenWolf)我发现了一个声明,翻译成英文如下(由我编号的句子):
In some cases it can be necessary that you need to duplicate a file descriptor [1]. 在某些情况下,您可能需要复制文件描述符[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]. 这样做的一个例子是,如果父进程想要与子进程交换数据,并且子进程通过使用exec*()
[2]被新进程覆盖。 In such a case, withoutdup() or dup2()
, the close-on-exec flag would be set [3]. 在这种情况下,如果没有dup() or dup2()
,将设置close-on-exec标志[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]. 设置此标志后,所有文件描述符都将变为无效(因为被新进程覆盖) - 也就是说,它们不再存在[4]。 The communication between the parent and child process would thus be stopped [5]. 因此,父母和子女过程之间的沟通将被停止[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]. 另一方面,如果使用dup() or dup2()
复制文件描述符,则删除close-on-exec标志,并且新覆盖的进程可以使用此文件描述符进行通信[6]。
I believe that the above paragraph contains several misleading statements or even errors. 我认为上段包含一些误导性陈述甚至错误。
In sentence [3], I do not understand why without the use of dup()
or dup2()
the close-on-exec flag would be set? 在句子[3]中,我不明白为什么不使用dup()
或dup2()
会设置close-on-exec标志?
The advice is wrong. 建议是错误的。 Close-on-exec is set only on file descriptors that your program has explicitly asked to be close-on-exec. Close-on-exec仅设置在程序明确要求为close-on-exec的文件描述符上。
The reasons you may choose to use dup2
may be: 您可能选择使用dup2
的原因可能是:
The description is also slightly misleading - it's only the new descriptor (ie the return value from dup()
or dup2()
) which has close-on-exec unset. 描述也有点误导 - 它只是新的描述符(即dup()
或dup2()
的返回值),它具有close-on-exec未设置。 The close-on-exec state of the original fd is unchanged. 原始fd的close-on-exec状态没有变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.