2015-04-23 46 views
1

我必須編寫一個c程序(linux)來在數組中搜索最大值,同時使用10個子項。數組大小爲1000.每個孩子從100個數字中搜索最大值。父母應該在管道上獲得結果。我的代碼不完美。主要問題是管道。父母只獲得第一個最大值。第二個問題是,孩子們沒有在同一時間運行(不是一個大問題,但可能有人可以告訴我什麼是錯) 我爲我的代碼做了一些筆記,但我的英語是如此糟糕的sry。 我希望我以正確的形式複製源代碼。使用叉子和管道在數組中搜索最大值

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



int main() 
{ 
int array[1000];  //main array 
int i; 
srand (time(NULL));  //for not the same numbers 
for(i=0;i<1000;i++){ //array upload 
array[i]= (rand() % (10000+1)); //from 1 to 10000 random numbers 
} 
int searchminindex; //search index, 0-100,100-200, etc 
int searchmaxindex; 
int threads = 10; //number of threads 
int fd[2]; 
pipe(fd); 
int arraymax[10]; //the 10 max numbers 
for(i=0;i<threads;i++){    //for 10 threads 
if(fork() == 0){ 
    close(fd[0]);    //close reading 
    searchminindex=i*100;   //number of thread * arraysize/threadsnumber 
    searchmaxindex=(i+1)*100; 
    int maxindex=searchminindex;   //it will store the max number index, start from the search min index 
    int j; 
    for(j=searchminindex;j<searchmaxindex;j++){ //max search 
     if(array[maxindex]<array[j]){ 
      maxindex=j; 
     } 
    } 
    write(fd[1], &array[maxindex], sizeof(array[maxindex])); //write the max number into the pipe 
    printf("max: %d\n", array[maxindex]); //that for check the result, will be deleted from the final code 
    close(fd[1]);    //close write 
    wait(NULL); 
    exit(0); 
} 
else{ 
wait(NULL); 
close(fd[1]);    //close write 
read(fd[0], &arraymax[i], sizeof(arraymax[i])); //read the max and store in arraymax[] 
close(fd[0]);     //close read 
printf("the read max from the pipe: %d\n", arraymax[i]); //that for check the result, will be deleted from the final code 
} 
} 

int arraymaxi=0;  //it is search the max in the main array for check the result, will be deleted 
int k; 
for(k=0;k<1000;k++){ 
if(array[arraymaxi]<array[k]){ 
    arraymaxi=k; 
} 
} 
printf("maxi: %d\n", array[arraymaxi]); //end of checking the correct result, will be deleted 
int l;     //check the max numbers from the forks, will be deleted 
for(l=0;l<10;l++){ 
printf("from the pipe max: %d\n", arraymax[l]); 
} 
int h;     //search the true max from the 10 numbers 
int truemaxindex=0; 
for(h=0;h<10;h++){ 
if(arraymax[truemaxindex]<arraymax[h]){ 
    truemaxindex=h; 
} 
} 
printf("the final max: %d\n", arraymax[truemaxindex]); 
return 0; 

回答

2

在每次撥打fork之後,您會等待剛完成創建的過程。在等待任何一個進程之前,您應該創建所有進程。

您還有其他一些錯誤。在循環的每一遍中關閉fd[1],但在循環的下一個循環中嘗試讀取它。如果您願意,您可以爲每個孩子使用不同的管道,但是如果要爲所有孩子使用相同的管道,則需要將管道保持打開狀態,直到您閱讀完所有回覆。

另外,不要在子女中撥打exit!當父母的atexit處理程序運行多次時,這可能會導致非常令人驚訝的行爲。您可以使用_exit

+0

謝謝!我徹底關閉並等待,現在它完美地工作!所有的孩子在同一時間運行,父母得到所有結果。但是,我可以在哪裏關閉讀寫?第一次後?或沒有必要關閉? – AsdFork

+0

@AsdFork如果不需要,您應該關閉管端。如果你考慮它,*兩個*端必須在fork循環期間保持打開狀態,因爲每個子進程都需要寫入端,並且父進程最終需要讀取端。順便說一句,你的代碼的一個簡單的改編,也解決了你的併發問題[可以在這裏看到](http://pastebin.com/zUnUPGPN)。祝你好運。 – WhozCraig

0

在父級的for循環中,您在第一次迭代時關閉管道的讀取側,因此第二次迭代中的讀取失敗。將閉環移到循環外部。 (並檢查錯誤!!)