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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With