2017-05-08 110 views
0

我試圖運行這塊的Hello World代碼:GETPID()返回意外值

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/types.h> 

char string1[] = "\n Hello"; 
char string2[] = " World.\n"; 

int main(void) 
{ 

int childpid; 

if((childpid = fork()) == -1){ 
    printf("\n Can't fork.\n"); 
    exit(0); 
} 

else if(childpid == 0){ /* Child process */ 
    printf("\n Child: My pid = %d, Parent pid = %d \n", getpid(), getppid()); 
    exit(0);  
} 

else{ /* Parent Process */ 
    printf("\n Parent: Child pid = %d, My pid = %d, Parent pid = %d \n", childpid, getpid(),getppid()); 
    exit(0); 
} 

} 

對於孩子的父母PID每次我得到的輸出是不同的:

~$ ./f 

Parent: Child pid = 6394, My pid = 6393, Parent pid = 27383 

Child: My pid = 6394, Parent pid = 1842 

~$ ./f 

Parent: Child pid = 6398, My pid = 6397, Parent pid = 27383 

Child: My pid = 6398, Parent pid = 6397 

當我檢查到pid = 1842屬於哪個進程時,我發現它是/sbin/upstart --user的pid。任何人都請解釋這些結果。

+0

我無法重現您的問題。您粘貼的代碼顯示我的機器上的預期行爲 –

回答

4

您有競賽狀況。有時候,你的父母會更快一點,當你看到這個奇怪的結果(不同的父母ID)時,就是這種情況。

在家長裏面睡了一會兒,看看會發生什麼。

事實上,你可以等待你的孩子:waitpid函數

... 
int status; 
waitpid(childpid, &status, 0); 
printf("\n Parent: Child pid = %d, My pid = %d, Parent pid = %d \n", childpid, getpid(),getppid()); 
exit(0); 
...