2016-10-02 53 views
2

在這個程序中,爲什麼子進程打印錯誤ppid()?子進程打印出錯ppid()

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

void childprocess() 
{ 
    printf("Child: Hi I am the child process\n"); 
    printf("Child: My process id is %d\n", getpid()); 
    printf("Child: My parent is %d\n", getppid()); 
    printf("Child: I am exiting\n"); 
} 

void parentprocess() 
{ 
    printf("Parent: Hi I am the parent process\n"); 
    printf("Parent: My process id is %d\n", getpid()); 
    printf("Parent: My parent is %d\n", getppid()); 
    printf("Parent: I am exiting\n"); 
} 

int main() 
{ 
    pid_t n = fork(); 
    if(n<0) 
    { 
     perror("fork failed:"); 
     exit(EXIT_FAILURE); 
    } 
    else if(n==0) 
     childprocess(); 
    else 
     parentprocess(); 
} 

輸出:

Parent: Hi I am the parent process 
Parent: My process id is 21550 
Parent: My parent is 7452 
Parent: I am exiting 
Child: Hi I am the child process 
Child: My process id is 21551 
Child: My parent is 1810 
Child: I am exiting 

如果我重新執行。有時輸出是我所期望的,有時卻是意想不到的。

+1

嘗試添加一些sleep();在父進程中,我想你會得到你所期望的。這個問題可能是https://en.wikipedia.org/wiki/Orphan_process –

回答

1

找到原因了。那真是愚蠢。父節點首先結束,所以子節點(孤兒)正在被init進程採納。

在我的情況下,它是進程ID爲1810

暴發戶了Upstart是一個基於事件的替換老的/ sbin目錄/初始化

1

事實上,也沒有保證調度將首先安排兒子進程。在子進程運行之前,父進程可能會終止。而且,由於在Linux中每個進程都有一個父進程(交換進程除外),孤兒孩子被分配給init。

您可以添加wait(),以便父進程等待子進程。