I am exploring parent process & child processes concept in UNIX. I wrote this small code thinking that x no. or processes would get created. But it has created a different number -
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argv, char *argc[])
{
int i;
pid_t childpid;
for(i=0; i<3; i++)
{
childpid = fork();
if(childpid == -1)
{
perror("Failed to Fork");
return 1;
}
if(childpid == 0)
printf("You are in Child: %ld\n", (long)getpid());
else
printf("You are in Parent: %ld\n", (long)getpid());
}
return 0;
}
OUTPUT:
You are in Parent: 30410
You are in Child: 30411
You are in Parent: 30410
You are in Child: 30412
You are in Parent: 30411
You are in Parent: 30410
You are in Child: 30413
You are in Child: 30414
You are in Parent: 30412
You are in Parent: 30411
You are in Child: 30415
You are in Child: 30416
You are in Parent: 30413
You are in Child: 30417
I understand that in a fork()
situation a parent or a child might get preference in execution. That's is not bothering me, what's bothering me is the number of processes that are getting executed. Why is it 14? and not some 2^n number which is what would happen if we are executing fork(); fork(); fork()
i.e. fork's one after the other.
What am I missing?
UPDATE: One more clarification -
The
fork
function copies the parent memory image so that the new process receives a copy of the address space of the parent.
What does this mean? Does it mean -
- the child process starts executing after the
fork()
statement? - the child process gets a copy of the parent process variables? so if
x=3
above fork, will the child process see this x as 3?