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):
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].
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?
The advice is wrong. Close-on-exec is set only on file descriptors that your program has explicitly asked to be close-on-exec.
The reasons you may choose to use dup2
may be:
The description is also slightly misleading - it's only the new descriptor (i.e. the return value from dup()
or dup2()
) which has close-on-exec unset. The close-on-exec state of the original fd is unchanged.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With