【发布时间】:2016-05-01 14:56:40
【问题描述】:
我必须在包含 10 个子进程的 1000 个数字的数组中找到最大值(这样每个子进程只检查一百个值),而父进程只需要收集数据。 我已经完成了整个事情,但我一直在阅读这些值。
代码如下:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(){
int array[1000];
int i, j;
int pids[10];
int searchminindex;
int searchmaxindex;
int maxindex;
srand(time(NULL));
//fill up array with random numbers
for(i = 0; i < 1000; i++)
{
tomb[i] = random() % 5000;
}
//create 10 child processes
for (i = 0; i < 10; i++) {
if ((pids[i] = fork()) < 0) {
perror("fork");
abort();
}
else if (pids[i] == 0) {
searchminindex = i * 100;
searchmaxindex = (i+1) * 100;
//finding the biggest value
maxindex = searchminindex;
for(j = searchminindex+1; j < maxindex; j++) {
if( array[maxindex] < array[j])
maxindex = j;
}
}
}
for(i = 0; i < 10; i++){
//here's where I'd read the return values of the subarrays
}
return 0;
}
我尝试过使用管道和 WEXITSTATUS,但我真的很困惑,不知道在哪里关闭管道的一端以及类似的东西,而使用 WEXITSTATUS 我完全迷路了。
有什么可以帮忙的吗?
【问题讨论】:
-
多 t 标题会是更好的选择
-
您反对为此使用线程吗?这会让事情变得容易一些。
-
你可以添加一个全局数组 pidsresults[10] 然后让每个 pid 将其结果放在它自己的索引中吗?
-
@JohnZwinck 是的,我们只是在课堂上学习分叉,所以我不应该为此使用线程。
-
所以不应该是家庭作业解决者,恕我直言。
标签: c process pipe fork wexitstatus