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

查看:99
本文介绍了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?

推荐答案

正在发生的事情是,父项在子项运行之前终止.这会使孩子成为孤儿,并且被根进程采用PID为1的子进程.如果您延迟或从stdin读取数据,而不是让父进程终止,您将看到预期的结果.

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的wiki链接

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()函数旨在允许父进程挂起自身,直到子进程的状态改变.因此,在if语句的父级分支中调用wait()会导致父级等待子级终止.

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天全站免登陆