关于execv和进程家族关系的一个问题
进程fork后,fork出来的儿子调用execv,结果还是父亲的儿子吗?
After a process forks and the forked son invokes execv, is the result still the son of the father?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
fork 创建一个称为 PARENT 的 CHILD 的新进程...exec 用进程 exec 替换当前正在运行的程序,因此仍然是 PARENT 的 CHILD 进程...
fork creates a new process called the CHILD of the PARENT.....exec replaces the current running program with the process exec'd and therefore remains the CHILD process of the PARENT...
是的。 execv 不会创建新进程 - 这就是为什么您需要首先分叉。
Yes. execv doesn't create a new process - that's why you need to fork first.
是的。此外,术语“进程族”与“进程组”非常接近,而“进程组”是一个非常重要的概念。
Yes it is. Also the terminology "process family" is uncomfortably close to "process group" which is quite an important concept.
你走在正确的轨道上。基本上,旧 UNIX 中的 fork(2) 系统调用创建了分叉进程的副本,具有新的 PID 和新的进程堆栈,并复制内存空间来执行此操作。 exec 使用新映像加载现有进程。您可以在大多数 shell 的
exec
操作中看到该版本的一个版本 - 它在 shell 占用的进程中取消所需的映像。当您 fork 一个进程时,fork 系统调用将返回新进程的 PID(如果您是父进程)或 0(如果您是子进程)。子进程还继承所有打开的文件描述符,特别是 0、1 和 2,它们通常称为 STDIN、STDOUT 和 STDERR。
(小测验:你认为 shell 如何管理重定向,例如使用
>
?)具有更大地址空间的更现代的 UNIX 变体(原始 UNIX 总共只有 64K 字!)实现了一个称为 < em>vfork 仅复制进程开始运行所需的子集,并依赖内存管理器在需要时提取其余部分。由于大多数情况下 fork 后面紧接着 exec,无论如何它都需要加载新映像,所以这是一个重要的优化。
马赫更进一步;当您创建一个新的 pprocess 时,除了执行上下文所需的内容之外,不会复制任何内容;图像完全相同。仅当进程更改内存中的位置时才会发生复制,此时包含该位置的页面将被复制。这称为“写入时复制”,并且几乎是最佳的。
You're on the right track. Basically, the fork(2) system call in in old UNIX created a copy of the process that forked, with a new PID and a new process stack, copying the memory space to do it. The exec loads the existing process with a new image. You can see one version of that in the
exec
operation in most shells -- it uns the desired image in the process that was occupied by the shell.When you fork a process, the fork system call returned the PID of the new process, if you're the parent, or 0 if you're the child. The child process also inherits all open file descriptors, in particular 0,1, and 2, which are more commonly known as STDIN, STDOUT, and STDERR.
(Pop quiz: how do you suppose a shell manages redirection, eg with
>
?)More modern UNIX variants with larger address spaces (the original UNIX only had 64K words total!) implementa variant fork called vfork that only copies the necessary subset of the process to start running, and depends on the memory manager to pull in the rest if needed. Since most times fork is immediately followed by exec, which needs to load a new image anyway, this is a significant optimization.
Mach takes that a step further; when you create a new pprocess, nothing is copied except what you need for an execution context; the image is exactly the same. Copying only happens when the process changes a location in memory, at which point the page containing that location is copied. This is called "copy on write", and is nearly optimal.