2012-04-26 31 views
0

嘿,我似乎迷路了。我應該能夠在一個無限循環內增加一個孩子的計數,並且每當家長髮送一個信號時,每隔1秒打印一次計數。我寫了我的代碼,但我認爲使用fork後,子進程和父進程同時運行,但事實並非如此,所以我不知道如何解決這個問題。任何幫助將是巨大的如何在使用睡眠功能時增加計數? (用C語言)

#include <stdio.h> 
#include <unistd.h> 
#include <signal.h> 
int count = 0;//global count variable 

void catch(int signal){ 
printf("Ouch! - I got signal %d \n", signal); 
printf("count is %d\n", count); 
count = 0; 
} 

int main(){ 
int pid; 
int sec=0; 
pid = fork(); 
int count1 = 0; 
(void) signal(SIGALRM, catch); 
if(pid==-1){ 
    printf("error\n"); 
} 
else if(pid==0){//if child 
    while(1){//while loop to increment count while parent to sleeping 
    count = count + 1; 
    } 
    //pause(); 

    } 
else{//parent 
    sleep(1);//1 second pause 
    raise(SIGALRM);//send alarm 
    count1 = count1 + 1; 
    if(count1>=5){ 
     return 0; 
    } 
    exit(0); 
} 
return 0; 

}

+0

http://stackoverflow.com/questions/10328956/how-do-you-increment-a-count-while-using-the-睡眠功能 – cnicutar 2012-04-26 08:12:21

+0

請使用編輯按鈕對您的問題進行更改,而不要再次詢問基本相同的問題 – 2012-04-26 09:15:30

回答

0

raise將信號發送到自己(即父母)不給孩子。使用kill(child_pid, SIGALRM)

0

使用fork之後,兩個進程的變量位於不同的內存位置。因此,當您在父進程中引發一個信號時,打印出來的是父進程的「count」變量。您可以在子進程的循環內打印「計數」以查看它增加