1

I am trying to understand about fork calls and tried to implement one by myself, In the following code, I am trying to calculate the number of children but apparently although I have increment the variables, the variables always output 0,

After reading a lot about this on the internet I found that this happens because The parent and the child each have their own private memory maps and one process cannot change the value of another process variables. I tried to make the variables global using extern and yet i am getting the output 0, can anyone tell me any other way of doing this?



int main(int argc, char *argv[]){
pid_t pid=fork();
int child=0;
int grchild=0;
    if(pid==0){
        printf("Child =>PPID:%d\n Child PID %d\n",getppid(),getpid());
        child=child +1;
        pid_2=fork(); //This is another fork call
        if(pid_2 == 0)
        {//This is the grand child process
            grchild++;
            child= child +2;
                    
        }
        else if(pid_2<0){
        exit(1);
        }
        else {
            exit(0);
        }
    }
    else if(pid<0){
    exit(1);
    }
    else    { 
        printf("Count of children and grandchildren are = %d,%d\n",child,grchild);
        }
    exit(0);
}
Weman
  • 63
  • 4

0 Answers0