4

在我在 Mac 上运行的 C/C++ 服务器应用程序(达尔文内核版本 10.4.0)中,我正在分叉子进程并希望这些子进程不继承服务器的文件句柄(文件、套接字、管道......)。似乎默认情况下所有句柄都被继承,甚至更多,netstat 显示子进程正在侦听服务器的端口。我怎么能做这样的叉子?

4

3 回答 3

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.

于 2012-10-24T16:15:09.987 回答
2

不,您需要自己关闭它们,因为只有您知道哪些需要保持打开状态。

于 2012-10-24T16:10:38.163 回答
0

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

于 2012-10-24T16:13:44.870 回答