【发布时间】:2021-03-26 21:03:20
【问题描述】:
如何等待所有分叉的进程终止,然后打印在一个
中计算的最终值
多变的。我有以下c程序。它通过分布数组来计算数组的总和
在使用 fork() 的 10 个不同线程中。但是当我退出创建
的 for 循环时
fork() 并打印一个多次打印的值。
typedef struct
{
int start;
int end;
} range;
int main(int argc, char *argv[])
{
int a[100];
int totalSum = 0;
for (int i = 0; i < 100; i++)
a[i] = 1;
int num_processes = 10;
int pipefd[2 * num_processes][2];
pid_t cpid;
char buf;
for (int i = 0; i < 2 * num_processes; i++)
{
if (pipe(pipefd[i]) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < num_processes; i++)
{
cpid = fork();
if (cpid == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0)
{
/* Child reads from pipe */
close(pipefd[i][1]); /* Close unused write end */
range *rangePtr = malloc(sizeof(range));
int sum = 0;
while (read(pipefd[i][0], rangePtr, sizeof(range)) > 0)
{
int start = rangePtr->start;
int end = rangePtr->end;
for (int i = start; i <= end; i++)
sum += a[i];
}
write(pipefd[num_processes + i][1], &sum, sizeof(sum));
close(pipefd[i][0]);
close(pipefd[num_processes + i][1]);
break;
}
else
{ /* Parent writes argv[1] to pipe */
/* Close unused read end */
range *rangePtr = malloc(sizeof(range));
rangePtr->start = i * 10;
rangePtr->end = i * 10 + 9;
close(pipefd[i][0]);
write(pipefd[i][1], rangePtr, sizeof(range));
close(pipefd[num_processes + i][1]);
close(pipefd[i][1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
int sum;
while (read(pipefd[num_processes + i][0], &sum, sizeof(sum)) > 0)
{
totalSum += sum;
}
close(pipefd[num_processes + i][0]);
// write(STDOUT_FILENO, &totalSum, sizeof(totalSum));
}
}
printf("%d\n", totalSum);
_exit(EXIT_SUCCESS);
}
在上面,我期望在 for 循环之外的 totalSum 变量的值
只打印一次。但我看到了
0
10
20
30
40
50
60
70
80
90
100
作为输出。这可能是什么原因?
【问题讨论】: