如何fork进程没有继承句柄? [英] How to fork process without inheriting handles?
问题描述
在我运行在Mac(Darwin Kernel版本10.4.0)的我的C / C ++服务器应用程序中我要求子进程,并希望这些子进程不继承文件句柄(文件,套接字,管道...)服务器。看来默认情况下所有句柄都被继承,甚至更多,netstat显示子进程正在监听服务器的端口。
通常,在 fork()
但之前,exec()
会有 getrlimit(RLIMIT_NOFILE,fds);
,然后关闭所有文件描述符 fds
。
此外, close-on-exec
可以使用 fcntl()
在文件描述符上设置,以便它们在 exec()
上自动关闭。然而,这不是线程安全的,因为另一个线程可以 fork()
在此线程打开一个新的文件描述符之后,之前它设置 close-on -exec
标志。
在Linux上,此问题已通过添加 O_CLOEXEC
到 open()
的函数,以便不需要额外的调用来设置 close-on-exec
p>
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?
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.
这篇关于如何fork进程没有继承句柄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!