Reputation: 499
I am a new C++ programmer and I am trying to figure out how parent and processes works. To do this, I tried to create three processes based on the codes here. However, I understand that we should exit after create our child processs each time to allow other child processes but I do not understand that in the second for loop, we we wait(NULL) for three times. Why are we doing this? It is my first time trying to understand parent and child process. I'd glad if you give me a source to study as well. Thanks!
int main(){
cout<<" Dad process is "<<getpid()<<endl;
for(int i=0;i<3;i++){
if(fork()==0)
{
cout<<"Son pid "<<getpid()<<" from pid "<<getppid()<<endl;
exit(0);
}
}
for(int i=0;i<3;i++){
wait(NULL);
}
}
`
Upvotes: 2
Views: 2248
Reputation: 2580
When you call wait(NULL), you're asking the OS to wait for a "state change" on any child process. State change includes the child going from the running state to the exited state.
You should probably be calling waitpid(childid) instead, so that you're specific about what child you're waiting for. In other words:
int child_id = fork();
if (child_id == 0)
{
/* do useful child work */
}
else
{
waitpid(child_id, ...);
}
Why wait for a child?
Firstly, you're normally asking the children to do useful work, and you want to know when they're finished.
Another reason is that the OS needs to keep some data for that process even if it has exited, until you call wait(). So by not calling wait, your children end up as "zombie" processes (you'll see them in top
).
You can see some typical real-world use here:
https://github.com/deplinenoise/tundra/blob/master/src/ExecUnix.cpp#L102
And docs you can find here:
https://linux.die.net/man/2/wait
Upvotes: 1
Reputation: 118340
Without the wait()
call, the parent process will immediately terminate, while the child processes may continue running.
For a short, brief program like the one shown here, it doesn't matter much.
But for a larger, more complex application, where the child processes perform substantial work: having the parent process terminate will be confusing. It leaves the impression that the process that's just been executed is done with its work. You're back at the command/shell prompt, without being immediately aware of that the child processes are still doing whatever they're doing.
Furthermore, if one of the child processes encounters an error and terminates with a non-zero exit code, the wait()
ing parent process can collect the exit code, and terminate itself with a non-zero exit code, indicating that the process has failed.
Upvotes: 2
Reputation: 11434
Quote from https://linux.die.net/man/2/wait :
...used to wait for state changes in a child of the calling process, and obtain information about the child whose state has changed. A state change is considered to be: the child terminated...
and some other things, but essentially here the purpose is to wait for the termination of the child processes.
Upvotes: 0