Search code examples
cprocessforkpid

Wrong PID in other processes


Take a look on this code

int main(int argc, char **argv) 
{
int pid[3];
int i,tmp;
pid[0]=getpid();


if((tmp=fork()) == 0) 
{
    pid[2]=getpid();
    printf("3. PIDY %d %d %d\n", pid[0], pid[1], pid[2]);
}
else
{
    pid[2]=tmp;
    if((tmp=fork()) == 0)
    {
        pid[1]=getpid();
        printf("2. PIDY %d %d %d\n", pid[0], pid[1], pid[2]);
    }
    else
    {
        pid[1]=tmp;         
        printf("1. PIDY %d %d %d\n", pid[0], pid[1], pid[2]);
    }
}
return 0;
}

On the output im getting smth like that:

1. PIDY 101 102 103
2. PIDY 101 102 103
3. PIDY 101 0 103

Im wondering why im getting pid[1] = 0 in 3rd process? Any idea how to fix it?


Solution

  • The process that prints the 3. line has already forked off before anything sets pid[1]. It's not in shared memory, so no values can be stored into it from the other processes, and you never initialized it, so it contains memory dirt, only coincidentally 0.

    If the array was declared as a global variable or if it were a static in a function, then the elements would have been initialized to 0 unless already initialized. initial value of int array in C would be a good read.