问题描述
如何等待所有分叉进程终止,然后打印
中计算出的最终值
多变的。我有以下 c 程序。它通过分布数组来计算数组的总和
在 10 个不同的线程中使用 fork()。但是当我退出创建
的 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],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],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
作为输出。这可能是什么原因?
解决方法
每个子进程都进入了if (cpid == 0)
语句,最后是break;
,所以子进程退出循环,循环后继续,即继续执行命令{{ 1}}。
如果您不想这样,只需将 printf("%d\n",totalSum);
替换为 break;
。