为什么子级的getppid()返回1 [英] Why getppid() from the child return 1

查看:346
本文介绍了为什么子级的getppid()返回1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行程序

#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

The PID of parent of child is 1

应该是3071吗?

推荐答案

因为当孩子要求其父项的pid时,父进程已完成.

Because parent process is finished by the time the child asks for its parent's pid.

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

When a process finishes, all its children are reassigned as children of the init process, which pid is 1.

尝试在父母的代码中使用 wait() 来等待孩子执行.然后,它应该会按预期工作.

Try using wait() in parent's code to wait for the child to execute. It should then work as you expect.

这篇关于为什么子级的getppid()返回1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆