1 year ago

#343307

test-img

Chocode

C: Storing Child process id in another array but not working

I am trying to make an array that stores all the Child process id, and then use them later, however it doesn't seem like working.

int numChild = 3;
int childPid[numChild+1];
int childPid2[numChild+1]; //stores the ChildPid 
int AllPid[numChild+1];
for(int i=1;i<= numChild; i++){ 
    if(fork() == 0){    
        childPid[i] = getpid();
        printf("Child %d pid %d from [parent] pid %d\n",i,childPid[i],getppid());
        childPid2[i] = childPid[i];
        exit(0);
    } else{
        AllPid[i] = getpid();
    }
}
for (int i=0; i < numChild; i++){
    wait(NULL);
} 
for(int i=1;i<= numChild; i++){ //
    printf("Child %d pid %d from [parent] pid %d\n",i,childPid2[i],getppid());
}   

The result is:

Child 1 pid 37917 from [parent] pid 37916
Child 2 pid 37918 from [parent] pid 37916
Child 3 pid 37919 from [parent] pid 37916
Child 1 pid 0 from [parent] pid 21171
Child 2 pid -3 from [parent] pid 21171
Child 3 pid 0 from [parent] pid 21171

Maybe I'm not understanding this concept well, but I don't understand why the pid (37917, 37918, 37919) can't be stored in the array. Thank you.

c

fork

pid

0 Answers

Your Answer

Accepted video resources