Quote:
Originally Posted by mitsulas
As I can observe instead of two children(as I expect) processes there are three.
|
Why would you expect two?
Quote:
This is because child process 4356 creates its own child.
|
You even understand why there are three.
Quote:
Under which circumstances this happens?
|
Everything except the return value of fork() is duplicated between the parent and child, so after the fork() the child will do exactly the same things the parent does except where those things depend on the return value of fork().
You did not make continuing through the loop until
i is 2 depend on that return value. (see alternate code below)
Quote:
Why all the messages of the type
"This is child X i=Y" are concentrated one under another?
|
The processes happened to execute in that sequence.
Too general a question to answer.
Quote:
Is affected by the fact that I have a dual-core processor?
|
The sequence in which the processes execute is probably affected by the fact that you have a dual-core processor.
If you
wanted just the two child processes you say you
expected, notice where I added
break to your code in the version below. That means the child does not stay in the loop so it does not create its own child.
Code:
int main()
{
int i=0;
pid_t pid;
for(i=0;i<2;i++)
{
pid=fork();
if(pid==0){
printf("This is child %i i=%i\n",getpid(),i);
break;
}
else{
printf("Parent: chid_pid=%i i=%i parent's pid=%i\n",pid,i,getpid());
}
}
exit(0);
}