2013-04-18 108 views
7

我運行程序爲什麼getppid()從孩子返回1

#include<stdio.h> 
#include <unistd.h> 
main() 
{ 
    pid_t pid, ppid; 
    printf("Hello World1\n"); 
    pid=fork(); 
    if(pid==0) 
    { 
     printf("I am the child\n"); 
     printf("The PID of child is %d\n",getpid()); 
     printf("The PID of parent of child is %d\n",getppid()); 
    } 
    else 
    { 
     printf("I am the parent\n"); 
     printf("The PID of parent is %d\n",getpid()); 
     printf("The PID of parent of parent is %d\n",getppid());   
    } 
} 

輸出我得到了。

$ ./a.out 
Hello World1 
I am the parent 
The PID of parent is 3071 
The PID of parent of parent is 2456 
I am the child 
The PID of child is 3072 
The PID of parent of child is 1 

我不可能不懂行

孩子的家長的PID爲1

應該已經3071?

+0

你可以通過添加適當的fflush(NULL);(在fork之前)和sleep(1);調用(在if和else的一部分中)來觀察你期望的行爲,就在'main'結束之前)。 –

回答

12

由於父進程在孩子要求其父母的pid時完成。

當一個進程完成後,其所有的孩子都再分配作爲init進程,其中PID是1

嘗試在父母的代碼中使用wait()等待孩子來執行的兒童。它應該像你期望的那樣工作。

0

pid 1用於初始化進程,看起來父進程在孩子可以打印之前完成。

如果編輯這樣else部分: -

else 
    { 
     printf("I am the parent\n"); 
     printf("The PID of parent is %d\n",getpid()); 
     printf("The PID of parent of parent is %d\n",getppid()); 
     while(1); 
    } 

你應該可以看到正確的輸出。