Reputation: 59
Even when i run the part of the code which outputs something only in the child process but the output is coming many times. like here i gave chunks=8 but the output is like 100+ times.
Here is the code:
#include<stdio.h>
#include<string.h>
int main(){
int chunks=8;
int proc[25];
for(int proc_iter=0;proc_iter<chunks;proc_iter++){
proc[proc_iter]=fork();
if(proc[proc_iter]==0){
printf("I am getting called with i=%d",proc_iter);
}
}
return 0;
}
Upvotes: 1
Views: 181
Reputation: 224157
This issue here is that the child process is performing the same loop as the parent process, so it forks as well.
If you set chunks
to 2 and add the following loop after the initial loop:
for (int i=0;i<chunks;i++){
printf("pid %d, i=%d, proc[i]=%d\n",getpid(),i,proc[i]);
}
You'll get output that looks something like this:
I am getting called with i=0
pid 30955, i=0, proc[i]=30956
pid 30955, i=1, proc[i]=30958
pid 30957, i=0, proc[i]=0
pid 30957, i=1, proc[i]=0
pid 30956, i=0, proc[i]=0
pid 30956, i=1, proc[i]=30957
I am getting called with i=1
pid 30958, i=0, proc[i]=30956
pid 30958, i=1, proc[i]=0
On the first iteration of the loop, one new process is created. Then both processes separately iterate the loop a second time and each forks another child. All four processes then complete the loop.
If you don't want the child processes to loop as well, have the child call exit
:
if (proc[proc_iter]==0) {
printf("I am getting called with i=%d\n",proc_iter);
exit(0);
}
Then the output will look something like this:
I am getting called with i=0
I am getting called with i=1
pid 31020, i=0, proc[i]=31021
pid 31020, i=1, proc[i]=31022
Upvotes: 2