简体   繁体   English

C:dup和close-on-exec

[英]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, without dup() 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 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]. 另一方面,如果使用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 process to be executed expects its I/O to be via particular file descriptors (usually 0, 1, and 2, corresponding to standard input, output and error streams respectively), or 要执行的进程要求其I / O通过特定的文件描述符(通常为0,1和2,分别对应于标准输入,输出和错误流),或者
  • the process will close some file descriptors, for whatever reason, and you need this fd to be outside the range to be closed. 无论出于何种原因,该过程将关闭一些文件描述符,并且您需要此fd超出要关闭的范围。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM