2

My code is forking a process and printing each process' PID and PPID. I was expecting the child's PPID to be same as the parent's PID, but it is not coming up as such.

I'm using Ubuntu 14.04.

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

int main(){
    int pid;
    pid = fork();
    if(pid==0){
        printf("\nI am the child and my parent id is %d and my id %d\n", getppid(), getpid());
    }
    else
        printf("\nI am the parent and my pid is %d and my parent id is %d\n", getpid(), getppid());

    return 0;
}

Here is the output I am getting:

I am the parent and my pid is 29229 and my parent id is 27087
I am the child and my parent id is 1135 and my id is 29230
John WH Smith
  • 15,880
Beginner
  • 123

1 Answers1

5

My guess is: the parent returned before the child, which became an orphan. PID 1135 must be your user init process, which became the process' new parent. (there are 2 subreapers in a Ubuntu user session).

$ ps -ef | grep init
you    1135    ...    init --user

If you want your parent to wait for its child, use wait. You actually have the include already:

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

int main(){
    int pid;
    pid = fork();
    if(pid == 0)
        printf("\nI am the child and my parent id is - %d and mine id %d\n",getppid(),getpid());
    else{
       printf("\nI am the parent and my pid is %d and my parent id is %d\n",getpid(),getppid());
       wait(NULL);
    }
    return 0;
}

This will ensure that the parent doesn't exit before the child's printf. You can see this behaviour more clearly by inserting a few sleep() calls here and there to see in which order things occur.

For more information on subreapers, have a look here.

John WH Smith
  • 15,880
  • Thanks,Earlier I was doing examples on zombie process and was not able to understand the ppid of 1135,Now I get it – Beginner Oct 01 '16 at 20:56
  • Note to you and the OP: fork() may return -1 in case of error. You should handle that in your code. – ott-- Oct 01 '16 at 21:26
  • @ott Indeed! However I will keep that out of the answer's code (based on the OP's), since it's also outside of the question's scope. The fork and wait man pages will provide information on such things. – John WH Smith Oct 01 '16 at 21:28