2016-12-03 94 views
0

我想用fork()創建一個兒子(1),並且這個兒子需要創建另一個兒子(2)。如何使用fork()來創建一個子進程?

兒子(1)和父親需要等待他們的兒子的結束給出信息。我希望他們所有人都可以使用printf他們的PID。

這是我的代碼:

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

int main(){ 

    int pid; //i know thats not good 

    if((pid = fork()) == 0) { //this isnt good either 
    printf ("SON %d\n",getpid()); 

    } else { 
    // sleep(1) not necessary 
    printf ("Thats the Father\n"); 
    printf ("PID of my Son PID %d\n",pid); 
    } 
} 

發現了一些相關信息來創建多個孩子在1對父親的,但我不知道,如何創建一個新的子出來的孩子。

+1

進程是性別中立的。 '叉子'創造一個「孩子」,而不是「兒子」。 –

回答

1

找到幾個信息來創建多個孩子出1父親,但我不知道,如何創建一個新的孩子出來的孩子。

這與您如何創建第一個子進程完全相同。您需要在子進程中再次fork()才能創建另一個進程。使用wait(2)來等待子進程。

考慮的例子(沒有錯誤檢查):

#include <stdio.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/wait.h> 
int main(void){ 

pid_t pid; 

if((pid = fork()) == 0) { 
    printf ("Child process: %d\n", (int)getpid()); 
    pid_t pid2; 

    if ((pid2 = fork()) == 0) { 
     printf("Child's child process: %d\n", (int)getpid()); 
    } else { 
     int st2; 
     wait(&st2); 
    } 
} else { 
    printf ("Parent process: %d\n", (int)getpid()); 
    int st; 
    wait(&st); 
} 

return 0; 
} 
0

感謝偉大的反應。知道了。

我的實際代碼:

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

int main(void){ 

int pid; 
int pid2; 
int st; 
int st2; 

if((pid = fork()) == 0) { 
    printf ("Kind: %d\n",getpid()); 

    if ((pid2 = fork()) == 0) { 
     printf("Kindes Kind process: %d\n",getpid()); 
    } else { 
       wait(&st2); 

    } 
} else { 
    printf("Ich warte auf meinen Sohn\n"); //WAITING FOR MY SON 
    wait(&st); 
    printf("mein Sohn ist fertig\n"); // MY SON IS RDY 
     printf ("Vater process: %d\n", getpid()); 
    printf("Vater: Status = %d\n",st); //MY STATUS AS A FATHER 
} 

return 0; 
} 

我的結果:

Ich warte auf meinen Sohn //waiting for my son 
Kind: 2175 //pid children 
Kindes Kind process: 2176 // childrens child pid 
mein Sohn ist fertig //my son finished 
Vater process: 2174 //father pid 
Vater: Status = 0 //father status 

我唯一的問題是,第一個孩子的PID打印出第一。 我想要孩子等待自己的孩子,並打印出他自己的孩子。

像:

waiting for my Son(2) 
pidchild2 
my son2 finished 
status 
waiting for my son 
pidchild1 
my son1 finished 
father pid 
status 

編輯:

得到了它,我認爲

剛剛給printf超越WAIT2。很明顯

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

int main(void){ 

int pid; 
int pid2; 
int st; 
int st2; 

if((pid = fork()) == 0) { 


    if ((pid2 = fork()) == 0) { 
     printf("Kindes Kind process: %d\n",getpid()); 
    } else { 
    printf("Ich warte auf meinen Sohn1\n"); 
       wait(&st2); 
    printf("mein Sohn ist fertig2\n"); // MY SON IS RDY 
    printf ("Kind: %d\n",getpid()); 
    printf("Sohn1: Status = %d\n",st2); //MY STATUS AS A FATHER 

    } 
} else { 
    printf("Ich warte auf meinen Sohn\n"); //WAITING FOR MY SON 
    wait(&st); 
    printf("mein Sohn ist fertig\n"); // MY SON IS RDY 
     printf ("Vater process: %d\n", getpid()); 
    printf("Vater: Status = %d\n",st); //MY STATUS AS A FATHER 
} 

return 0; 
}