How to fork process without inheriting handles?

2019-07-04 12:22发布

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?

标签: c++ c posix fork
3条回答
Summer. ? 凉城
2楼-- · 2019-07-04 12:32

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

查看更多
倾城 Initia
3楼-- · 2019-07-04 12:35

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

查看更多
smile是对你的礼貌
4楼-- · 2019-07-04 12:38

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.

查看更多
登录 后发表回答