This should use dup3() or fcntl(F_DUP2FD_CLOEXEC) where possible.