2015-09-26 49 views
2

我試圖在運行fork()命令後打印pid的進程。這裏是我的代碼 -在外殼的叉指令打印進程ID

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

int main(void) 
{ 
    int pid; 
    pid=fork(); 
    if(pid==0) 
     printf("I am the child.My pid is %d .My parents pid is %d \n",getpid(),getppid()); 
    else 
     printf("I am the parent.My pid is %d. My childs pid is %d \n",getpid(),pid); 
    return 0; 
} 

這是回答我getting-

I am the parent.My pid is 2420. My childs pid is 3601 
I am the child.My pid is 3601 .My parents pid is 1910 

爲什麼在2號線的父母不ID。爲什麼2420我收到1910我怎樣才能得到這個值?

+0

'INT PID;'應該被定義爲'將爲pid_t PID;'有父'waitpid函數()'上了孩子,所以當孩子叫'getppid()'父仍在運行。 'fork()'函數有三個返回值:= 0表示孩子,> 0表示父母,<0表示錯誤。總是檢查所有三個條件,不要認爲操作成功 – user3629249

回答

8

父母在孩子執行其printf調用之前正在退出。當父母退出時,孩子會得到新的父母。默認情況下,這是PID 1的init進程。但最新版本的Unix增加了一個進程聲明自己是「subreaper」的能力,它繼承了所有孤兒。 PID 1910顯然是你的系統中的次要因素。有關詳細信息,請參見https://unix.stackexchange.com/a/177361/61098

在父進程中放入一個wait()調用,使其在等待子進程繼續之前等待它退出。

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

int main(void) 
{ 
    int pid; 
    pid=fork(); 
    if(pid==0) { 
     printf("I am the child.My pid is %d .My parents pid is %d \n",getpid(),getppid()); 
    } else { 
     printf("I am the parent.My pid is %d. My childs pid is %d \n",getpid(),pid); 
     wait(NULL); 
    } 
    return 0; 
}