【问题标题】:Error in file descriptors of a pipe管道的文件描述符错误
【发布时间】:2017-11-29 17:42:45
【问题描述】:

运行这个评估指数泰勒展开的 c 程序,使用在每个循环中创建的子进程将这个总和的一个数字返回给父进程,它导致我出现错误的文件描述符错误,尽管我不知道为什么,我认为问题可能出在我打开和关闭循环中的管道等方面。

我的代码是:

#include<unistd.h>
#include<stdio.h>
#include<sys/wait.h>
#include<stdlib.h>
int main()  
{int i; pid_t id;
int count=1;
int fact=1;
int N;
double S=1;double s1=0; double div;double x;
int p[2];

printf("Input x and N : \n");
scanf("%lf %d",&x,&N);
if(pipe(p) == -1)
{perror("Error opening pipe");
return -1; }
 else{ 
 for(i=1;i<=N;i++)
 {  id=fork();
  if(id==0)
  { close(p[0]);
      while(count<i)
      {   fact*=(fact+1);
                      x*=x;
          count++;
      }

    div=x/fact;
    if(write(p[1],&div,sizeof(double))!=sizeof(double))
    perror("file writing error");
    exit(0);
  }
  else {
      wait(NULL);
      close(p[1]); \\ ***<-- Problem here*** 
      if(read(p[0],&s1,sizeof(double))!=sizeof(double))
{
 perror("file become empty");         
 return -1;}
      S+=s1;
  }}}
printf("Sum = %lf",S);
return 1;}

【问题讨论】:

    标签: c pipe


    【解决方案1】:

    在 fork 之后关闭管道的各个读/写端,而不是之前。

    【讨论】:

    • 仍然,现在在读写时,我收到同样的错误信息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    相关资源
    最近更新 更多