4

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?

Mihran Hovsepyan
  • 10,810
  • 14
  • 61
  • 111

3 Answers3

11

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.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • If you're going to do `exec`, you can just configure all your FDs to "close on exec". But I was under the impression that the OP wasn't going to `exec` anything... – Kerrek SB Oct 24 '12 at 16:16
  • @KerrekSB true, but one still may like to do the closing loop just to make sure no file descriptor gets leaked into the new process because setting `close-on-exec` was overlooked somewhere. – Maxim Egorushkin Oct 24 '12 at 16:22
  • @KerrekSB and you may not control either one of the opens or one of the forks if you call some 3rd party API or even some OS function. – pilkch Jun 02 '15 at 03:37
2

Nope, you need to close them yourself since only you know which ones you need to keep open or not.

hexist
  • 5,151
  • 26
  • 33
  • I don't wan't to keep none of them opened. Is there some method for getting the all handles available in child after fork? – Mihran Hovsepyan Oct 24 '12 at 16:12
  • 2
    Hmm, well you could just do `for (i=0; i < 1024; ++i) close(i);`, or go higher if you have a whole lot of connections. (Or better yet use `getrlimit(RLIMIT_NOFILE, fds);` like @Maxim is using to get the highest fd you can have) – hexist Oct 24 '12 at 16:16
0

Basically no. You have to do that yourself. Maybe pthread_atfork help, but it still be tedious.

halfelf
  • 9,737
  • 13
  • 54
  • 63