子进程和父进程ID

6

我在子进程块中对父进程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);
  }

输出结果: 父进程中的pid为2642,子进程中的pid为2643

子进程可以使用getppid()函数获取父进程的pid,这是在“高级Unix编程”中所说的。但是在这里,我得到的是“1”,即“init”进程的pid。

请问如何在子进程块中获取父进程的pid值。请帮助我获得输出结果。

我在“Linux Mint OS”上执行了此程序,但在“WindRiver”OS上我没有遇到这个问题。这个程序会根据操作系统而改变行为吗?


可能是为什么从子进程中获取ppid()返回1的重复问题。 - melpomene
5个回答

6

这是因为父进程可以在子进程之前退出。如果父进程在没有请求其子进程的返回值的情况下退出,则子进程将被进程pid=1占用。这在经典UNIX或GNU系统SystemV init中都存在。

解决方案是在父进程中使用waitpid()

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

我在程序末尾加入了“sleep(2)”并且程序正常运行,你的答案是正确的。 - Santosh Sahu

0
#include <stdio.h>
#include <unistd.h>

int main()
{
  int pid,pid2;
  pid=fork();

  if (pid<0) {
    printf("fork failed");
    exit(-1);
  } else if (pid==0) {
    printf("child id is%d",getpid());
    execlp("/bin/ls","is",NULL);
    printf("\nsleeping for 2 seconds using pid of child class");
    sleep(2);

    printf("killing the child process");
    kill(getpid());
  } else {
    wait(NULL);
    printf("The parent id is %d\n",getpid());
    printf("The child id is %d\n",getpid());
    printf("\nsleeping for 3 seconds without pid");
    sleep(3);
    printf("\nchild completed\n");

    exit(0);
  }
}

4
提供一个解释来回答你的问题。 - Anantha Raju C
这是一个基本的C程序,用于计算子进程ID和父进程ID,包括sleep函数。 - Rishabh Kumar

0

当父进程执行完毕而子进程仍在运行时,子进程被称为孤儿(因为其父进程已死),如果您是以 root 登录的话(其 pid =1 ),则该子进程将被 init 进程接管。

如果您想让子进程在父进程之前退出,则可以使用 wait() 系统调用及其变体。


0
在 fork 之后,你会有两个新进程,并且父进程可以知道子进程的 ID,但反过来不行。如果你真的需要这样做,你需要在 fork 之前打开一个管道(popen),然后父进程可以把它写入管道中,而子进程可以读取它。

-1

这很简单,因为父进程不再存在。如果你调用wait()系统函数,它将一直存在,直到子进程完成其工作,并且你将获得父进程的PID。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接