问题
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?)
回答1:
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 calling setpgid()
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 calls setpgid()
). That is why the child process should also call setpgid()
(before calling exec()
).
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.
来源:https://stackoverflow.com/questions/6025673/why-is-there-timing-problem-while-to-fork-child-processes