I was checking behaviour of fork system call. I executed the following program.
#include<stdio.h>
int count=0;
int main()
{
int i;
int n=3;
for(i=1;i<=n;++i)
{
printf(" %d ",i);
fork();
}
}
I had a thought that having fork()
inside a for loop
is similar to writing it in series i.e.
for(i=1;i<=3;i++)
fork();
is similar to
fork();
fork();
fork();
I tried to draw a recursion tree for the same
I expected the output to be eight consecutive 3's. But output was following:
1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
Note:compiled and executed in gcc