July 26th, 2003, 04:53 PM
How the parent process create new process while it waits for the first process to end
I have created a child process. While that child process is doing something I want the parent to create two new processes.
I'm not sure if I have this right?
pid=fork(); //first child
//getpid should be the process id of the first child process.
//while parent waits for first child??
//it creates the new children????
July 26th, 2003, 05:53 PM
fork'ing can get tricky, because you normally don't want the child process go on to do the same things as the parent does, including creating more children while waiting for a child to exit. That is why we're taught the standard code:
So the point is that the second and third children would also need to be restricted to their own block of code and not be allowed to do the parent stuff.
if ((child_pid = fork()) == 0)
// what the child does
exit(0); // exit so that we don't go on to do the parent's stuff
// else we are the parent
// so carry on with doing the parent's stuff
Now, I believe that waitpid will block (suspend operation until the specified PID terminates or stops) unless the option (3rd argument) is set to WNOHANG. Also waitpid returns the PID of the process that had satisfied the wait or, with the WNOHANG option set, a zero if the child had not terminated, or -1 if an error occured (eg, ECHILD if there are no child processes). Therefore, its use in the while loop is questionable, especially since it would only loop if a child had terminated.
Also, assuming that WNOHANG is set, if you were to loop waiting for the first child and create two new child processes each time, then you could create a large number of them and, even worse, you would only know the PIDs of the last two you created.