SocketPair() currently calls socketpair() and then uses two fcntl() calls to set FD_CLOEXEC. If another thread forks between those calls, the descriptors can be inherited by the child and remain open across exec.
This change uses SOCK_CLOEXEC when available, setting the flag on both descriptors atomically when the socket pair is created. Platforms without support for it still use the existing fcntl() approach. If either call fails, both descriptors are closed.
The race came up in #311 and #312. It was recently brought up again by ValeraFinebits in bitcoin/bitcoin#36747, where ryanofsky expressed interest in reviewing an upstream fix.
Testing:
- All tests pass with the normal build and with
SOCK_CLOEXECdisabled at compile time. - The build also passes with
-Werror,-Wundefand-Wunused. straceconfirms that the spawn tests usesocketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, ...)without the subsequentfcntl(F_SETFD, FD_CLOEXEC)calls. On master, the same test produces two socket pairs followed by fourfcntl()calls.
This modifies the same function as #231, but only in the POSIX branch.