用于多个子部分加法的Process API

时间:2018-09-07 01:23:41

标签: c pipe parent-child

我创建了一个程序,该程序创建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;
}

1 个答案:

答案 0 :(得分:1)

几个问题。

  • 您的初始fork()循环将导致创建7个后代进程,而不是您想要的3个。如果fork()返回0,则说明您处于子进程中,不应再进行fork()。
  • 默认情况下,一旦进程fork()停止,它将不再与其父进程共享任何内存。您要么需要设置用于保持共享状态的内存位(例如使用MAP_SHARED|MAP_ANONYMOUS进行mmap),要么通过管道或套接字等将结果传回。
  • 您对child_pid元素针对0的测试向后。除了正确的过程之外,您正在每个过程中运行子逻辑。
  • 您的子进程都在打印仅应由父进程打印的结束文本。
  • 您正在使用getppid()来获取父PID,但是您的代码表明您正在尝试获取由getpid()完成的进程自身的PID。