electric
2012-09-21 23:58:08 UTC
#include
#include
int main()
{
pid_t pid;
/*fork a child process*/
pid=fork();
if(pid>0){/*error occurred*/
fprintf("stderr,"Fork Failed");
exit(-1);
}
else if(pid==0){/*child process*/
execlp("/bin/ls","ls",NULL);
else{/*parent process*/
/*parent will wait for the child to complete*/
wait(NULL);
printf("Child Complete");
exit(0);
}
}
PLEASE answer this.Does the child process which is created due to the fork() system call,execute ONLY those code segments that come AFTER the fork() statement in its parent process?My gut feeling says that it should be so otherwise if the child were to begin executing from the beginning of the main() function, then it will again create a child and this will lead to an infinite number of fork() creating infinite number of processes, isn't it??Or am I wrong to think that way?
While we are at it, please answer the following question which I had encountered in a sample question paper for an exam:
"If a process forks thrice, in all what is the total number of child processes that will be created as a result of it?"
I answer 7!! Please see if my reasoning is right or wrong.I feel 7 because, the original process forking thrice will create 3 child processes.The first child of the original process will get the copy of the same code and hence will create TWO child processes of its own( due to 2 fork() in it).The second child get a code segment with one fork() .Using this logic recursively,I found that the first child would case 2 more child processes while the 2nd child will create one more child process bringing the total to 7.Am I right?Please give your suggestions.THANKS.