为什么 fork 子进程时会出现计时问题
当我查看 gnu.org,我没有得到这一部分。
shell 还应该调用
setpgid
将其每个子进程放入新进程组中。这是因为存在潜在的时序问题:每个子进程在开始执行新程序之前都必须放入进程组中,而 shell 依赖于拥有所有组中的子进程继续执行之前。如果子进程和 shell 都调用 setpgid,则可以确保无论哪个进程首先访问它,都会发生正确的事情。
链接页面有两个方法,launch_job()
和launch_process()
。 它们都调用 setpgid
以防止计时问题。
但我不明白为什么会出现这样的问题。
我猜新程序意味着launch_process()
中execvp (p->argv[0], p->argv);
的结果。并且在运行execvp之前,setpgid(pid, pgid);
总是被执行,而在launch_job()
上没有相同的函数。
那么话又说回来,为什么会出现这样的问题呢? (为什么我们必须在 launch_job ()
上调用 setpgid ();
?)
When I took a look at the reference of 'Launching-Jobs' in gnu.org, I didn't get this part.
The shell should also call
setpgid
to put each of its child processes into the new process group. This is because there is a potential timing problem: each child process must be put in the process group before it begins executing a new program, and the shell depends on having all the child processes in the group before it continues executing. If both the child processes and the shell call setpgid, this ensures that the right things happen no matter which process gets to it first.
There is two method on the link page, launch_job ()
and launch_process ()
.
They both call the setpgid
in order to prevent the timing problem.
But I didn't get why is there such a problem.
I guess new program means result of execvp (p->argv[0], p->argv);
in launch_process()
. And before run execvp, setpgid (pid, pgid);
is always executed, without same function on launch_job ()
.
So again, why is there such a problem? (why we have to call setpgid ();
on launch_job ()
either?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是 shell 希望进程位于正确的进程组中。如果 shell 未对其子进程调用
setpgid()
,则在一段时间内子进程不属于进程组,而 shell 会继续执行。 (通过调用setpgid()
,shell 可以保证子进程在调用后是进程组的一部分)。还有另一个问题,即子进程可能在正确设置其进程组 id 之前(即在父进程调用
setpgid())代码>)。这就是为什么子进程还应该调用
setpgid()
(在调用exec()
之前)。诚然,描述相当糟糕。这里解决的不仅仅是一个问题;这实际上是两个不同的问题。一 - 父进程(即 shell)希望子进程位于正确的进程组中。第二 - 新程序只有在其进程已放入正确的进程组后才应开始执行。
The problem is that the shell wants the process to be in the right process group. If the shell doesn't call
setpgid()
on its child process, there is a window of time during which the child process is not part of the process group, while the shell execution continues. (By callingsetpgid()
the shell can guarantee that the child process is part of the process group after that call).There is another problem, which is that the child process may execute the new program (via
exec
) before its process group id has been properly set (i.e. before the parent callssetpgid()
). That is why the child process should also callsetpgid()
(before callingexec()
).The description is admittedly pretty bad. There isn't just one problem being solved here; it's really two separate problems. One - the parent (i.e. the shell) wants to have the child process in the right process group. Two - the new program should begin execution only once its process has already been put into the right process group.