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?
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
Basically no. You have to do that yourself. Maybe
pthread_atfork
help, but it still be tedious.Nope, you need to close them yourself since only you know which ones you need to keep open or not.
Normally, after
fork()
but beforeexec()
one doesgetrlimit(RLIMIT_NOFILE, fds);
and then closes all file descriptors lower thanfds
.Also,
close-on-exec
can be set on file descriptors usingfcntl()
, so that they get closed automatically onexec()
. This, however, is not thread-safe because another thread canfork()
after this thread opens a new file descriptor but before it setsclose-on-exec
flag.On Linux this problem has been solved by adding
O_CLOEXEC
flag to functions likeopen()
so that no extra call is required to setclose-on-exec
flag.