首先,在2014年,从来没有使用过vfork
但简单地说fork(2) http://man7.org/linux/man-pages/man2/fork.2.html。 (自从vfork(2) http://man7.org/linux/man-pages/man2/vfork.2.html自 POSIX 2001 起已过时,并在 POSIX 2008 中删除)。
然后,关闭大部分文件描述符的最简单方法就是
for (int fd=3; fd<256; fd++) (void) close(fd);
(hint: if a fd
is invalid, close(fd)
would fail and we ignore the failure; and you start from 3
to keep open 0==stdin, 1==stdout, 2==stderr; so in principle all the close
above would fail).
然而,行为良好且编写良好的程序在关闭时不需要这样的循环(因此这是克服以前的错误的粗略方法)。
当然,如果您知道除 stdin、stdout、stderr 之外的某些文件描述符是有效的并且子级需要program_call
(这不太可能)您需要明确跳过它。
然后使用FD_CLOEXEC
越多越好。
您的程序不太可能在您不知情的情况下拥有大量文件描述符。
也许你想要守护进程(3) http://man7.org/linux/man-pages/man3/daemon.3.html或(正如评论者vality https://stackoverflow.com/users/3323096/vality) posix_spawn http://pubs.opengroup.org/onlinepubs/009695399/functions/posix_spawn.html.
如果您需要显式关闭STDIN_FILENO
(即 0),或STDOUT_FILENO
(即 1),或STDERR_FILENO
(即2)你会更好open("/dev/null",
... and dup2
他们在打电话之后 - 打电话之前exec
,因为大多数程序都期望它们存在。