linux – 当子进程在创建后立即调用exec()或exit()时,为什么要使用vfork()?

操作系统概念和APUE说

With vfork(), the parent process
is suspended, and the child process uses the address space of the parent.
Because vfork() does not use copy-on-write, if the child process changes
any pages of the parent’s address space, the altered pages will be visible to the
parent once it resumes. Therefore, vfork() must be used with caution to ensure
that the child process does not modify the address space of the parent.

vfork()
is intended to be used when the child process calls exec() or exit() immediately after
creation.

我怎么理解最后一句话?

当vfork()创建的子进程调用exec()时,exec()是否通过加载新程序来修改父进程的地址空间?

当vfork()创建的子进程调用exit()时,exit()在终止子进程时是否不修改父进程的地址空间?

我更喜欢Linux.

谢谢.

解决方法:

When a child process created by vfork() calls exec(), doesn’t exec() modify the address space of the parent process, by loading the new program?

不,exec()为新程序提供了一个新的地址空间;它不会修改父地址空间.参见例如the discussion of the exec functions in POSIXthe Linux execve() manpage.

When a child process created by vfork() calls exit(), does exit() not modify the address space of the parent process when terminating the child?

普通的exit()可能 – 它运行由正在运行的程序(包括其库)安装的退出钩子. vfork()更具限制性;因此,在Linux上,it mandates使用_exit()而不调用C库的清理功能.

vfork()结果证明很难做对;它已在当前版本的POSIX标准中删除,而应使用posix_spawn().

但是,除非你真的知道你在做什么,否则你不应该使用vfork()或posix_spawn();坚持好老fork()和exec().

上面链接的Linux联机帮助页提供了更多上下文:

However, in the bad old days a fork(2)
would require making a complete copy of the caller’s data space,
often needlessly, since usually immediately afterward an exec(3) is
done. Thus, for greater efficiency, BSD introduced the vfork()
system call, which did not fully copy the address space of the parent
process, but borrowed the parent’s memory and thread of control until
a call to execve(2) or an exit occurred. The parent process was
suspended while the child was using its resources. The use of
vfork() was tricky: for example, not modifying data in the parent
process depended on knowing which variables were held in a register.

上一篇:如何在我的Android应用程序中访问raspberry.local?


下一篇:linux进程详解:fork进程、孤儿进程、僵尸进程(需重新传图)