日期:2014-05-16  浏览次数:20687 次

求助关于getpid(),getppid()的问题

 1 #include<stdio.h>
  2 #include<unistd.h>
  3 #include<stdlib.h>
  4 
  5 int main()
  6 {
  7     pid_t id;
  8     id=fork();
  9      if(id == -1)
10 {
11     perror("fujinchengdiaoyongshibai");
12 }
13      if(id == 0)
14     {
15         printf("child process id is %d,the father id is %d \n",getpid(),getppid());
16     }
17 
18     if(id > 0)
19     {
20         printf("father process id is %d,the father father id is%d\n",getpid(),getppid());
21     }
22     //  printf("PID = %d\n",getpid());
23     //  printf("PPID = %d\n",getppid());


为什么我得到的结果是呢?

father process id is 2531,the father father id is2335
child process id is 2532,the father id is 1 
父进程是2531,但是在子进程中得到的父进程却是1,按道理应该相等的,为什么不相等呢?

------解决方案--------------------
因为用fork函数创建子进程,父进程没有等待子进程的退出,这可能导致子进程编程孤儿进程,被init进程接管,所以父进程id为1
------解决方案--------------------
你可以采用vfork(),这样父进程会等待子进程退出,自身才会退出。上面的情况,是父进程先退出,子进程失去父进程,被init 1 进程(所有进程的父进程)收养