Le 07/01/2012 13:50, Lewin Bormann a écrit :
> My question: Because I did not find something about it anywhere, I'm just
> guessing that the flag has the effect of closing this fd when using a syscall
> from the exec() family? -> 'close-on-exec'. Is that right?
Yes.
More precisely, when you spawn a new process, you typically fork() and
exec*(). The fork() call preserves (dup) all file descriptors, and
exec*() keeps file descriptors opened for the new application (for
purely historical reasons) unless they have the FD_CLOEXEC (added later
in POSIX) flag.
The default, fixed behavior (ie. you can not change this insane^W
default mode), is to open files (open, fopen) with the FD_CLOEXEC flag
cleared, that is, to KEEP all file descriptors opened when executing
another application, which is generally not desirable (except for
stdin/out/err for obvious reasons).
The O_CLOEXEC feature is rather "new" (on Linux, it was introduced on
2.6.23 if I am not mistaken - using it before will make open to return
an error) but allows to atomically open a file with the FD_CLOEXEC flag
set. Setting this flag just after the open() is prone to race conditions
(ie. if another thread is doing fork/exec just after an open, the
corresponding flag will remain open), so the O_CLOEXEC mask is the only
clean solution to do things correctly. You do not need to fcntl() when
using it, of course.