Search code examples
cprocessoperating-systemglobal-variablesfork

C : Store PID in global variable


I am currently working on a school project and I wanted to store the PID of my process in the global array id, so that I can use it in another function :

int id[3];

int main(int agrc,const char* agrv[]) {
for(int i = 0; i < 3; i++) {
    if((fork() == 0)) {
        id[i] = (int)getpid();
        printf("ID[%d] = %d\n",i,id[i]);
        if(i != 3) {
            printf("I am a wharehouse. PID = [%d] PPID = [%d]\n",getpid(),getppid());
            whcode();
            exit(0);
        }
        else if(i == 3) {
            printf("I am the central. PID = [%d] PPID = [%d]\n",getpid(),getppid());
            central_code();
            exit(0);
        }
    }
}
sleep(2);

printf("ID[0] = %d\n",id[0]);
printf("ID[1] = %d\n",id[1]);
printf("ID[2] = %d\n",id[2]);

}

But when I run this the output of the last 3 prints is 0, where it should be the PID of each process. Why does this happen?


Solution

  • On the call to fork(), new process is created with separate virtual memory space. This child process will return from the call to fork with 0, so in your code, this child will go inside the if branch and assign to id[i] it's pid. But this assignment is happening in a separate process, with separate virtual memory, so it has no effect on the parents virtual memory space and the parent will not see any change in its array. That is why your code prints the zeroes.

    If you want to print the pids of the children by the parent, use the return value of fork(), which in parent is the pid of the child process. Inside the for, use code such as this:

    pid_t child_id;
    switch (child_id = fork()) {
        case -1:
            //Fork failed, exit with error or something
            break;
        case 0:
            //Child code
            printf("ID[%d] = %d\n",i,id[i]);
            if(i != 3) {
                printf("I am a wharehouse. PID = [%d] PPID = [%d]\n",getpid(),getppid());
                whcode();
                exit(0);
            }
            else if(i == 3) {
                printf("I am the central. PID = [%d] PPID = [%d]\n",getpid(),getppid());
                central_code();
                exit(0);
            }
            break;
        default:
           id[i] = child_id;
           break;
    }
    

    By the way, you should really declare the id array as pid_t id[3], and when printing, print it as long. That for now is probably the most portable way to handle these things.