Steffen Nurpmeso wrote, on 11 Nov 2025:
>
> || The safe counterpart for avoiding the same race with dup( ) is
> || the use of the F_DUPFD_CLOFORK or F_DUPFD_CLOEXEC action of the
> || fcntl( ) function.
>
> sounds definitive, whereas i stood in dead-end when coding.
The APPLICATION USAGE for fcntl() says:
In order to set both FD_CLOEXEC and FD_CLOFORK when duplicating a
file descriptor, applications should use F_DUPFD_CLOFORK to obtain
the new file descriptor with FD_CLOFORK already set, and then use
F_SETFD to set the FD_CLOEXEC flag on the new descriptor. (The
alternative of first using F_DUPFD_CLOEXEC and then setting
FD_CLOFORK with F_SETFD has a timing window where another thread
could create a child process which inherits the new descriptor
because FD_CLOFORK has not yet been set.)
The only loophole I can see in that method is that in between the two
fcntl() calls the fd would be leaked if the current process calls
exec, but that is an extremely unlikely thing for the process to do
(i.e. call exec in one thread while other threads are actively running).
If it does ever happen, it would be because the application has a bug
in its thread coordination.
--
Geoff Clare <[email protected]>
The Open Group, Apex Plaza, Forbury Road, Reading, RG1 1AX, England