getppid() not returning parent's pid [duplicate]

扶醉桌前 提交于 2019-12-11 02:43:52

问题


I have been trying to learn about fork and processes. I just encountered a small problem with this piece of code and was trying to understand why?. I was trying to duplicate a process by a system call Fork and with the value of pid being positive, it hit the parent and its getpid() was returned. And simultaneously it hit the child and its getpid() was returned. But the problem was, when I called up the getppid() here, it was expected to show its parent's process identifier, which happened to be 3370. But upon compilation and execution of this file, it showed the value of getppid() as 1517 (not parent's id).

I am using ubuntu 14.04 LTS on Oracle VM VirtualBox (32-bit O.S.). The code of this forking.cpp file is as follows:

#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);
}

For compilation, I was using the command g++ forking.cpp on terminal and for executing, ./a.out. Then it showed this:

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$ 

I know that trivially, if a parent dies before its child, the child is automatically adopted by the original "init" process, with PID 1. But here it is definitely not this case.


回答1:


This situation occurs when the parent process terminates before the execution of getppid(). Use wait(NULL) at the end the parent to solve the problem.



来源:https://stackoverflow.com/questions/24385235/getppid-not-returning-parents-pid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!