2015-04-23 47 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循环中,您在第一次迭代时关闭管道的读取侧,因此第二次迭代中的读取失败。将闭环移到循环外部。 (并检查错误!!)