c - getpid 和 getppid 返回两个不同的值

标签 c fork pid

当我运行下面的代码时

#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

parent 的 PID(20172) 与 child 的 parent ID (1) 有何不同?这两者不应该相等吗?

最佳答案

发生的事情是父进程在子进程运行之前终止。这使 child 成为孤儿,并被 PID 为 1 的根进程采用。如果您延迟或从标准输入读取数据而不是让父进程终止,您将看到您期望的结果。

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() 会导致父分支等待子分支终止。

关于c - getpid 和 getppid 返回两个不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15183427/

相关文章:

c - sigsuspend() 不对信号作出 react

c - 在 C 中实现管道?

c - 进程ID,waitpid

pid - 如何使用 spdlog 记录 pid(进程 ID)

c++ - 如何在 Windows 上获取父进程 ID

用源代码中的值替换变量的 C 编程工具

c++ - 在 C 或 C++ 中的位图上高效执行 bool 表达式

c - 按Q退出循环

bash - 杀死文件夹中的所有pid文件

c - Cello 库如何能够引入运算符和关键字的使用,即使它们不是 C 库的一部分?