【问题标题】:C fork two children and pipe between parent and childrenC fork两个孩子并在父母和孩子之间进行管道
【发布时间】:2013-05-05 00:38:54
【问题描述】:

我正在尝试 fork 两个孩子。父级读取一行发送到管道。子 1 读取它并将其写入另一个管道,最后子 2 读取它。但是,输出始终是父获取行。谢谢!

#define MAX 80

void child();
void parent();
void childtwo();
char * getli();
void printline(char *buffer, int count);
char * convertCase(char *str);

int pipe1[2]; 
int pipe2[2];
int main(int argc, char **argv)
{
  pipe(pipe1);
  pipe(pipe2);
  if(fork()){
    if(fork()){ 
      printf("1st\n");
      parent();
          exit(0);
    }
    else{
      printf("3rd\n");
      childtwo();
      exit(0);
    }   
  }
  else{
    printf("2nd\n");
    child();
    exit(0);
  }
}

void child(){
  char *buf;
  int count = 0;
  close(pipe1[1]); 
  close(pipe2[0]);   
  while(1){ 
  buf = (char *) malloc(sizeof(char)*MAX);
  read(pipe1[0], buf, MAX);
  if (strcmp(buf,"quit")== 0){
    printf("Child is leaving\n");
    free(buf);
    break;
  }
  else{
    printf("Child: ");
    printline(buf,strlen(buf));
    write(pipe2[1],buf, strlen(buf)+1);
    free(buf);
        }
  close(pipe2[1]);
  close(pipe1[0]);
  exit(0);
  }
}

void childtwo()
{
  char *buf;
  int count = 0;
  close(pipe2[1]);
  buf = (char *) malloc(sizeof(char)*MAX); 
  while(1){
    buf = (char *) malloc(sizeof(char)*MAX);
    read(pipe2[0], buf, MAX);
    if (strcmp(buf,"quit")== 0){
      printf("Childtwo is leaving\n");
      free(buf);
      break;
    }
    else{
      printf("Childtwo:");
      printline(buf,strlen(buf));
      free(buf);   
    }
  }
  close(pipe2[0]);
  exit(0);
}

void parent(){
  char * buffer;
  int count = 0, done=0;
  close(pipe1[0]);
  while (done != 1){
    printf("parent getting line: ");
    buffer = getli();
    write(pipe1[1],buffer, strlen(buffer)+1);
    if (strcmp(buffer,"quit")== 0){
      puts("parent goes away");
      free(buffer);
      break;
    }
    free(buffer);
  }
  close(pipe1[1]);
  exit(0);
}

【问题讨论】:

  • 您的子进程中存在内存泄漏,您在循环之前和循环内部分配了buf both
  • 感谢您的指出!但是删除它并没有解决问题
  • 您是否检查过所有系统调用是否真正工作?您应该检查他们返回的内容,例如read 返回 -1 然后出现一些错误,您可以使用例如perror 打印出错误。您应该为 所有 函数执行此操作,即使 fork 可能会失败。
  • 一个问题是您的进程没有足够快地关闭足够的文件描述符。在执行任何其他操作之前,父进程应关闭管道 1 的读取端和管道 2 的两个描述符。第二个孩子应该先关闭管道 1 的描述符和管道 2 的写入端,然后再执行任何其他操作。中间进程需要关闭管道 1 的写入端和管道 2 的读取端。如果您正在复制描述符(到标准输入和输出),您将需要执行更多关闭操作。
  • 你的程序不完整:undefined reference to `printline'undefined reference to `getli'

标签: c fork pipeline


【解决方案1】:

我的猜测是它适用于第一行,但不适用于其他任何一行。

这是因为第一个子进程(在child 函数中)在读取其输入后退出。您可能打算将 closeexit 调用放在循环之外。

【讨论】:

  • 不幸的是,它甚至第一次都不起作用。我关闭并退出循环但得到了相同的结果
猜你喜欢
  • 2015-01-18
  • 2017-08-26
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-20
  • 1970-01-01
  • 2013-02-26
相关资源
最近更新 更多