我创建了一个程序,该程序创建3个孩子并将每个数组发送给每个孩子,然后每个孩子计算该数组的总和并用进程ID打印它,然后将总和发送给父孩子将这些值相加并打印最终的总和。我的问题是,当我去运行代码时,在孩子部分求和和父求和之后,我得到了随机的子和父输出。
这是我的代码:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main ()
{
pid_t child_pid[3] ;
//Define the array to hold the set of numbers
int setNum[6] = {2,3,7,-1,10,6}, sum[3] = {0, 0, 0}, j;
//Display the parents process ID
printf("I am the parent with process ID: %d \n", (int) getppid());
//Create a process
for(j=0; j<3; j++)
{
child_pid[j] = fork();
}
j=0;
if (child_pid[0] != 0)
{
//calculate the sum
for(int i=0; i<2; i++)
sum[j] = sum[j] + setNum[i];
printf("I am the child with process ID: %d and I am sending %d to my parent\n", child_pid[0], sum[j]);
j=j+1;
}
if (child_pid[1] != 0)
{
//calculate the sum
for(int i=2; i<4; i++)
sum[j] = sum[j] + setNum[i];
printf("I am the child with process ID: %d and I am sending %d to my parent\n", child_pid[1], sum[j]);
j=j+1;
}
if (child_pid[2] != 0)
{
//calculate the sum
for(int i=4; i<6; i++)
sum[j] = sum[j] + setNum[i];
printf("I am the child with process ID: %d and I am sending %d to my parent\n", child_pid[2], sum[j]);
j=j+1;
}
//Print the parent with final sum
int final_sum = sum[0] + sum[1] +sum[2];
printf("I am the parent with process ID: %d with a final sum of %d\n", (int) getppid(), final_sum);
return 0;
}
答案 0 :(得分:1)
几个问题。
MAP_SHARED|MAP_ANONYMOUS
进行mmap),要么通过管道或套接字等将结果传回。