2014-09-27 192 views
-2

我有痛苦大量試圖弄清楚這個問題了。所以,我想要做的是創建3個來自父進程的子進程。我已經想通了,但問題是我的程序退到第三個孩子離開孤兒時(我想)。這是我的第一代的過程代碼:fork函數涉及for循環

int i = 0; 
int corpse; 
int status; 
pid_t child; 
about("Dad"); 
printf("Now .. Forking !!\n"); 

about("Dad"); 
for(i=0; i<3; i++){ 
child = fork(); 

    if (child == 0){ 

    about ("son"); 
    break; 

    }else if (child < 0){ 

    perror ("Unable to fork!"); 
    break; 
    } 

} 

void about(char * msg) 
{ 
pid_t me; 
pid_t old; 

me = getpid(); 
old = getppid(); 

printf("[%s] Hi, my pid is %d and I come from %d.\n", msg, me, old); 
} 
while ((corpse = wait(&status)) > 0){ 
    printf("Child process PID=%d terminates\n", corpse); 
} 

現在我的輸出如下:

[Dad] Hi, my pid is 2940 and I come from 2883. 
Now .. Forking !! 
[Dad] Hi, my pid is 2940 and I come from 2883. 
[son] Hi, my pid is 2941 and I come from 2940. 
[son] Hi, my pid is 2942 and I come from 2940. 
Child process PID=2941 terminates 
Child process PID=2942 terminates 
[son] Hi, my pid is 2943 and I come from 2940. 
Child process PID=2943 terminates 
+1

顯示你的*實際代碼*。用「continue」語句顯示代碼但沒有循環是沒有意義的。 – 2014-09-27 13:41:09

+1

你沒有第三個孩子。你只分了一次。 – 2014-09-27 13:42:34

+0

我添加了for循環,對不起,我複製了錯誤的東西。 – 2014-09-27 13:52:18

回答

1

如果我能得到它的權利,你是擔心孩子的過程,成爲孤兒,然後您可以使用等待或waitpid。通過使用任何這些,父進程可以等待子進程終止。 如需更多幫助,請使用「男士等待」。