Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fork process without inheriting handles?

Tags:

c++

c

fork

posix

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?

like image 994
Mihran Hovsepyan Avatar asked Dec 12 '22 21:12

Mihran Hovsepyan


1 Answers

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.

like image 96
Maxim Egorushkin Avatar answered Dec 24 '22 04:12

Maxim Egorushkin