简体   繁体   中英

child process prints wrong ppid()

In this program, why is child process printing wrong ppid()?

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

void childprocess()
{
  printf("Child: Hi I am the child process\n");
  printf("Child: My process id is %d\n", getpid());
  printf("Child: My parent is %d\n", getppid());
  printf("Child: I am exiting\n");
}

void parentprocess()
{
   printf("Parent: Hi I am the parent process\n");
   printf("Parent: My process id is %d\n", getpid());
   printf("Parent: My parent is %d\n", getppid());
   printf("Parent: I am exiting\n");
}

int main()
{
    pid_t n = fork();
    if(n<0)
    {
      perror("fork failed:");
      exit(EXIT_FAILURE);
    }
    else if(n==0)
       childprocess();
    else
       parentprocess();
}

Output:

Parent: Hi I am the parent process
Parent: My process id is 21550
Parent: My parent is 7452
Parent: I am exiting
Child: Hi I am the child process
Child: My process id is 21551
Child: My parent is 1810
Child: I am exiting

If I re-execute. Sometimes the output is what I expect and sometimes it is unexpected.

Found the reason.That was stupid. The parent is ending first, so the child(orphan) is getting adopted by init process.

In my case it is the Upstart with process id 1810.

Upstart is an event-based replacement for the /sbin/init

Indeed, there is no guarantee that the scheduler will schedule the son process first. Parent process might terminate before son process is run. And since in Linux every process has a parent process (with exception to swapper process), the orphan child is assigned to init.

You can add a wait() so that parent process wait for child process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM