2014-04-17 28 views
0

我需要捕獲CTRL + C並完成子項,主進程必須等到完成它的東西,然後程序才能完成。 這是我的代碼:以C捕獲信號並殺死所有的孩子

void sigint_handler() 
{ 
    /*do something*/ 
    printf("killing process %d\n",getpid()); 
    exit(0); 
} 

int main() 
{ 
    signal(SIGINT, sigint_handler); 


    printf ("This is the parent. PID=%d\n",getpid()); 

    int num_children = 4; 

    int i; 

    while (1){ 

    for (i=0; i<num_children ;i++){ 

    if (fork()==0){ 

    printf ("This is children %d\n",getpid()); 

    sleep(1); 

    exit(0); 

    } 

    } 

    //Rest Parent code 
    sleep (1); 

    printf ("This is the parent again %d, children should have finished\n",getpid()); 

    //Do stuff 

    } 

} 

這是輸出:

This is the parent. PID=19317 
This is children 19318 
This is children 19319 
This is children 19321 
This is children 19320 
^Ckilling process 19321 
killing process 19320 
killing process 19317 
killing process 19318 
killing process 19319 

我該如何處理這¿?我不想殺害父母,只是孩子,提前謝謝你!

+1

切勿在信號處理程序中使用printf。這不是可重入的。 – JeremyP

回答

0

現在是像這更好:

void sigint_handler() 
    { 
     /*do something*/ 
     printf("killing process %d\n",getpid()); 
     exit(0); 
    } 

    int main() 
    { 



    printf ("This is the parent. PID=%d\n",getpid()); 

    int num_children = 4; 

    int i; 
    int pid; 
    int status; 

    while (1){ 

    for (i=0; i<num_children ;i++){ 

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

     signal(SIGINT, sigint_handler); 

    printf ("This is children %d\n",getpid()); 

    sleep(1); 

    exit(0); 

     } 

    } 

    //Rest Parent code 
    sleep (1); 

    waitpid(pid,&status,0); 

    printf ("This is the parent again %d, children should have finished\n",getpid()); 


    } 


} 

它完成第一殺死孩子,但waitpid函數似乎什麼都不做,這是輸出:

This is the parent. PID=20048 
This is children 20049 
This is children 20050 
This is children 20051 
This is children 20052 
This is the parent again 20048, children should have finished 
This is children 20053 
This is children 20054 
This is children 20056 
This is children 20055 
^Ckilling process 20056 
killing process 20055 
killing process 20053 
killing process 20054 

而我要的就是打印最後:這是2004年的父母,孩子應該已經完成​​,然後完成。 非常感謝

0

在信號處理程序kill中,僅子進程。在父親程序wait中,讓孩子在退出之前退出。

+0

我不得不用另一個答案回答你(下面就是這樣)1條評論是不夠的 – aDoN

0

進行此更改,

for (i=0; i<num_children ;i++){ 

    if (fork()==0){ 
signal(SIGINT, sigint_handler); 
    printf ("This is children %d\n",getpid()); 

    sleep(1); 

    exit(0); 

    } 

    } 

if (fork()==0)滿足條件的獨生子女流程,使獨生子女進程將被註冊到被抓住信號並退出。