GETPID和getppid返回两个不同的值 [英] getpid and getppid returns two different values

查看:166
本文介绍了GETPID和getppid返回两个不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行下面

#include <stdio.h>
# include <sys/types.h>
//int i=0;
int main(){

int id ;
id = fork() ;
printf("id value : %d\n",id);
    if ( id == 0 )
    {
    printf ( "Child : Hello I am the child process\n");
    printf ( "Child : Child’s PID: %d\n", getpid());
    printf ( "Child : Parent’s PID: %d\n", getppid());
    }
    else
    {
    printf ( "Parent : Hello I am the parent process\n" ) ;
    printf ( "Parent : Parent’s PID: %d\n", getpid());
    printf ( "Parent : Child’s PID: %d\n", id);
    } 

}

我的输出

id value : 20173
Parent : Hello I am the parent process
Parent : Parent’s PID: 20172
Parent : Child’s PID: 20173
id value : 0
Child : Hello I am the child process
Child : Child’s PID: 20173
Child : Parent’s PID: 1

如何能在父母的PID(20172)从孩子的父母的ID不同(1)?应该不是这两个相等?

How can the parent's PID(20172) differ from the child's parent's ID (1)? Shouldn't those two be equal?

推荐答案

这是怎么回事的是,孩子运行之前父终止。这留下孩子作为一个孤儿,它被用的1 PID根进程采纳如果你把延误或从标准,而不是让家长终止你会看到你所期望的结果读取数据。

What's happening is that the parent is terminating before the child runs. this leaves the child as an orphan and it gets adopted by the root process with PID of 1. If you put a delay or read data from stdin rather than letting the parent terminate you'll see the result you expect.

流程 ID 1通常是init进程启动和关闭系统的主要原因。在init(简称初始化)是一个守护进程,这是所有其他进程的直接或间接的祖先。 维基链接初始化

Process ID 1 is usually the init process primarily responsible for starting and shutting down the system. The init (short for initialization) is a daemon process that is the direct or indirect ancestor of all other processes. wiki link for init

作为user314104指出wait()和waitpid函数()函数被设计为允许父进程暂停,直到自己的一个子进程的状态发生改变。这样一个呼叫等待()中的的父分支如果语句会导致母体等待子终止。

As user314104 points out the wait() and waitpid() functions are designed to allow a parent process to suspend itself until the state of a child process changes. So a call to wait() in the parent branch of your if statement would cause the parent to wait for the child to terminate.

这篇关于GETPID和getppid返回两个不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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