Process parent ID of child process is different from PID of parent

Viewed 3951

I'm trying to work with multiple processes in Linux using fork() function in C, this is my code:

p1 = fork();

if(p1 != 0){
    p2 = fork();
}

printf("My PID is %d\n",getpid());
printf("My parent PID is %d\n",getppid());

Now let's assume the parent process ID is 100, and the two child processes (p1, p2) IDs are 101 & 102, and the init process PID will be 0 my expected output is:

My PID is 100
My parent PID is 0

My PID is 101
My parent PID is 100

My PID is 102
My parent PID is 100

Instead i see something different, the two child processes have the same PPID but the first process has a different PID from that. Here is a sample output i got:

My PID is 3383
My parent PID is 3381

My PID is 3387
My parent PID is 1508

My PID is 3386
My parent PID is 1508

My question is, shouldn't the parent PID of the two child processes be 3383? Hope someone can explain how it all works here and what am i doing (or thinking) wrong.

2 Answers
Related