How to fork process without inheriting handles?
c, c++, fork, posix
Solution
Normally, after `fork()` but before `exec()` one does `getrlimit(RLIMIT_NOFILE, fds);` and then closes all file descriptors lower than `fds`.
Also, `close-on-exec` can be set on file descriptors using `fcntl()`, so that they get closed automatically on `exec()`. This, however, is not thread-safe because another thread can `fork()` after this thread opens a new file descriptor but before it sets `close-on-exec` flag.
On Linux this problem has been solved by adding `O_CLOEXEC` flag to functions like `open()` so that no extra call is required to set `close-on-exec` flag.
Problem
In my C/C++ server application which runs on Mac (Darwin Kernel Version 10.4.0) I'm forking child processes and want theses childes to not inherit file handles (files, sockets, pipes, ...) of the server. Seems that by default all handles are being inherited, even more, netstat shows that child processes are listening to the server's port. How can I do such kind of fork?