从管道内的进程传递整数数组

时间:2019-05-18 11:07:36

标签: c process pipe fork

我必须解决C语言中的问题。我有两个过程,P1和P2。 P1接受一个整数数组,然后将其发送给P2,P2必须仅检查此数组中的质数,然后对其进行修改并发送回P1,P1必须打印修改后的数组。

示例: 整数数组(myArr)= {3,9,17,21,4,2,5} 最终结果= {3,0,17,0,0,2,5}

问题是,如何发送整数槽管道数组?

 //parent process
  if(p>0)
   {
    int i;
    int printArr[N];

    close(fd1[0]);
   //myArr is an array of integers previously declared
    write(fd1[1],myArr,N);


    close(fd1[1]);


    wait(NULL);

    close(fd2[1]);
    read(fd2[0],printArr,N);

    printf("\nPrinting modified array: ");
    for(i=0; i<N; i++)
    {
        printf("\t%d",printArr[i]);
    }

    close(fd2[0]);


}

 //child process
 else if(p==0)
   {
    int i,k;
    close(fd1[1]);
    int readArr[N];

    read(fd1[0],readArr,N);

            //here's the problem, it doesn't print correct values
    printf("Array that comes from parent");
    for(i=0; i<N; i++)
    {
        printf("\n%d\n",readArr[i]);
    }


    for(i=0; i<N; i++)
    {
        k=checkprime(readArr[i]);
        if(k==1)
            readArr[i]=0;
    }

    close(fd1[0]);
    close(fd2[0]);

    write(fd2[1],readArr,sizeof(readArr)+1);
    close(fd2[1]);

    exit(0);
      }

当我注释代码时,当我从管道将数组读取到readArr时,它无法正确打印。

1 个答案:

答案 0 :(得分:2)

您的read()调用正在将N个字节读入N int个数组中。使用read(fd, buf, N * sizeof(int))。看来您也需要修复write()