【问题标题】:getppid() not returning parent's pid [duplicate]getppid()不返回父母的pid [重复]
【发布时间】:2014-08-14 15:11:46
【问题描述】:

我一直在尝试了解 fork 和进程。我刚刚在这段代码中遇到了一个小问题,并试图理解为什么? 我试图通过系统调用Fork 复制一个进程,并且pid 的值为正,它击中了父进程并返回了它的getpid()。同时它击中了孩子,并返回了它的getpid()。但问题是,当我在这里调用getppid() 时,它应该显示其父进程标识符,恰好是3370。 但是在编译和执行这个文件时,它显示getppid() 的值为1517(不是父母的id)。

我在 Oracle VM VirtualBox(32 位操作系统)上使用 ubuntu 14.04 LTS。这个forking.cpp文件的代码如下:

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <cstdlib>

using namespace std;

int main()
{
    pid_t pid1;
    pid1 = fork();
    if(pid1 == -1)
    {
        cout << "No child process formed: " << getpid() <<endl;
    }
    else if(pid1 == 0)
    {
        cout << "Child has been formed: " << getpid()<< " and its parent's id: " << getppid() << endl;
    }
    else if(pid1 > 0)
    {   
        cout << "Parent process has been called: " << getpid() << endl;

    }

    cout << "END of Stuffs" << endl;
    return 0;
    exit(0);
}

为了编译,我在终端上使用了命令g++ forking.cpp,而为了执行,我使用了./a.out。 然后它显示了这个:

Parent process has been called: 3370
END of Stuffs
Child has been formed: 3371 and its parent's id: 1517
END of Stuffs

shashish-vm@shashishvm-VirtualBox:~/Desktop$ 

我知道很简单,如果父母在其孩子之前去世,孩子会自动被原始“init”进程收养,PID 1。但这里绝对不是这种情况。

【问题讨论】:

  • 无法重现,运行代码时两个 ppid 与此处预期的相同。
  • 你必须在父母中等待孩子。 Example.
  • 如果父进程在子进程到达它的getppid() 之前倒下,进程id 将在运行表中被替换。 wait(NULL) 在你的 parent if-block 中,在它的输出之后作为 n.m 建议应该让你到达那里(除非在重新定义世界的调试器中运行,这并不完全不常见)。
  • 是的,你是对的,我试过了,它成功了。不过,我担心为什么父进程在子进程执行之前终止?。
  • 我的意思是,在这种情况下,我既不是sleep-ing 子进程也不是让它停止。因此,理想情况下,这两个过程应该并行运行并最终同时显示结果。

标签: c++ linux pid fork


【解决方案1】:

这种情况发生在父进程在getppid()执行之前终止。在父级末尾使用wait(NULL)解决问题。

【讨论】:

    猜你喜欢
    • 2021-07-16
    • 2021-10-27
    • 1970-01-01
    • 2013-12-22
    • 2013-02-17
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多