Carlos Romero
Carlos Romero

Reputation: 181

Trying to store the PID's of every child process

I am currently learning about the fork() function in c. I was playing around with the child pid's and trying to store them within an array but keep coming across errors:

void store(int pid){
    int arr[10];
    int i = 0;
    for(i = 0; i < 10; i++){
        if(arr[i] == 0){
            arr[i] = pid;
            printArray(arr);
            break;
        }
    }
}

int stuff(int a){
    int status = fork();

    if(status == 0){
        printf("PID IS %d\n", getpid());
        store(getpid());
    }
    else {
        printf("PID IS %d\n", getpid()); 
        store(getpid());
    }

    return a + 1;
}

int main(int argc, char * argv[]){
    int a = stuff(10);

    return 0;
}

Instead, this outputs the same array with the two different PIDS in the same array index. I am not too sure what exactly is happening here and would be grateful for any explanation.

Upvotes: 0

Views: 2976

Answers (1)

Paul
Paul

Reputation: 1657

Keep it in mind that fork function is called once but returns twice. The difference in the returns is that the return value in the child is 0, whereas the return value in the parent is the process ID of the new child. The child process and the parent process run in separate memory spaces.

That's the reason why your program outputs the same array with the two different PIDS in the same array index.

int stuff(int a){
    int status = fork();

    // fork will return a value of pid_t type
    pid_t status = fork();

    if(status == 0){
        // this is in the child process, so getpid() will return the pid of the child
        printf("PID IS %d\n", getpid());
        store(getpid());
    }
    else {
        // this is in then parent process, so getpid() will return the pid of the parent
        printf("PID IS %d\n", getpid());
        store(getpid());
    }

    return a + 1;
}

Upvotes: 2

Related Questions