Search code examples
linuxpidchild-process

Why does PPID change?


This is my code:

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    pid_t pid;
    int status;
    if ((pid = fork()) < 0) {
        printf("Fork failed.");
    } else if (pid == 0) {
        printf("CHILD:\nPID: %d, PPID: %d, UID: %d\n", pid, getppid(), getuid());
    } else {
        wait(&status); //wait for child to terminate
        printf("PARENT:\nPID: %d, PPID: %d, UID: %d\n", pid, getppid(), getuid());
    }   

    return 0;
}

This is the output:

CHILD:
PID: 0, PPID: 4309, UID: 1000
PARENT:
PID: 4310, PPID: 3188, UID: 1000

Why is 4309 the PPID of the child? Shouldn't it be 4310? Thnak you.


Solution

  • You didn't print out the parent's PID in the parent code, so you have nothing to compare it to. fork() returns the child's PID to the parent. In your example it appears that the parent has PID 4309 and the child 4310.