简体   繁体   English

子进程打印错误的ppid()

[英]child process prints wrong ppid()

In this program, why is child process printing wrong ppid()? 在此程序中,为什么子进程打印错误的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. 在我的情况下,它是进程号为1810的新贵。

Upstart is an event-based replacement for the /sbin/init Upstart是/ 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. 并且由于在Linux中,每个进程都有一个父进程(交换进程除外),因此将孤儿分配给init。

You can add a wait() so that parent process wait for child process. 您可以添加一个wait()以便父进程等待子进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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