子进程和父进程ID

San*_*ahu 5 c fork pid

刚刚与子进程块中的父pid值混淆.我的计划如下:

 int main(int argc, char *argv[])
  {
    pid_t pid;
    pid=fork();
    if(pid==-1){
            perror("fork failure");
            exit(EXIT_FAILURE);
    }
    else if(pid==0){
            printf("pid in child=%d and parent=%d\n",getpid(),getppid()); 
    }
    else{
            printf("pid in parent=%d and childid=%d\n",getpid(),pid);
    }
    exit(EXIT_SUCCESS);
  }
Run Code Online (Sandbox Code Playgroud)

输出:父级中的pid = 2642,子级= 2643

pid in child = 2643,parent = 1

在"高级Unix编程"中,它表示子进程可以使用getppid()函数获取父进程id.但在这里我得到"1",这是"init"进程ID.

如何在子进程块中获取父pid值..请帮助我获取输出.

我在"Linux Mint OS"中执行但在"WindRiver"操作系统中我没有遇到这个问题.该程序是否根据操作系统改变行为?

hek*_*mgl 6

那是因为父亲可以/将在儿子之前退出。如果父亲在没有请求其孩子的返回值的情况下存在,则孩子将被 pid=1 的进程拥有。什么是经典的 UNIX 或 GNU 系统 SystemV init。

解决方法是waitpid()在father中使用:

int main(int argc, char *argv[])
{
    pid_t pid;
    pid=fork();
    if(pid==-1){
        perror("fork failure");
        exit(EXIT_FAILURE);
    }
    else if(pid==0){
        printf("pid in child=%d and parent=%d\n",getpid(),getppid()); 
    }
    else{
        printf("pid in parent=%d and childid=%d\n",getpid(),pid);
    }

    int status = -1;
    waitpid(pid, &status, WEXITED);

    printf("The child exited with return code %d\n", status);
    exit(EXIT_SUCCESS);
}
Run Code Online (Sandbox Code Playgroud)