【问题标题】:Why getppid() from the child return 1为什么 getppid() 从孩子返回 1
【发布时间】:2023-04-08 17:35:02
【问题描述】:

我正在运行程序

#include<stdio.h>
#include <unistd.h>
main()
{
    pid_t pid, ppid;
    printf("Hello World1\n");
    pid=fork();
    if(pid==0)
    {
        printf("I am the child\n");
        printf("The PID of child is %d\n",getpid());
        printf("The PID of parent of child is %d\n",getppid());
    }
    else
    {
        printf("I am the parent\n");
        printf("The PID of parent is %d\n",getpid());
        printf("The PID of parent of parent is %d\n",getppid());        
    }
}

我得到的输出是。

$ ./a.out 
Hello World1
I am the parent
The PID of parent is 3071
The PID of parent of parent is 2456
I am the child
The PID of child is 3072
The PID of parent of child is 1

我听不懂这句话

孩子的父母的PID是1

应该是3071?

【问题讨论】:

  • 您将通过添加适当的fflush(NULL);(在fork 之前)和sleep(1); 调用(在if 的then 和else 部分,以及就在main 结束)。

标签: c linux process fork


【解决方案1】:

因为父进程在子进程请求其父进程的 pid 时已完成。

当一个进程完成时,它的所有子进程都被重新分配为 init 进程的子进程,pid 为 1。

尝试在父代码中使用wait() 等待子代码执行。然后它应该可以按预期工作。

【讨论】:

    【解决方案2】:

    pid 1 用于 init 进程,看起来父进程在子进程打印之前完成。

    如果你像这样编辑 else 部分:-

    else
        {
            printf("I am the parent\n");
            printf("The PID of parent is %d\n",getpid());
            printf("The PID of parent of parent is %d\n",getppid());   
            while(1);
        }
    

    您应该会看到正确的输出。

    【讨论】:

      猜你喜欢
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 2011-08-14
      • 2012-01-25
      • 2012-03-05
      • 2017-06-04
      • 2015-01-25
      • 2023-03-27
      相关资源
      最近更新 更多