C中通过管道进行通信

标签 c process pipe parent-child

我正在尝试编写这个小程序,其中父级和子级通过管道相互通信,这里的代码可以工作,除非您“取消注释”注释行,否则会出现某种死锁,并且我不明白为什么?有什么想法吗?

int main(int argc, char **argv){

  int fd[2];
  int fd2[2];
  pid_t pid;
  pipe(fd);
  pipe(fd2);
  pid = fork();

  if(pid==0){
      close(fd[1]);
      dup2(fd[0],fileno(stdin));
      close(fd2[0]);
      FILE *output = fdopen(fd2[1],"w");
      char buffer[255];
      while(fgets(buffer,255,stdin)!=NULL)
          printf("child: %s",buffer);
  //  fprintf(output,"%s",buffer);
  } else {
      close(fd[0]);
      close(fd2[1]);
      FILE *output = fdopen(fd[1],"w");
      char buffer[255];
      while(fgets(buffer,255,stdin)!=NULL)
          fprintf(output,"%s",buffer);
      //FILE *input = fdopen(fd2[0],"r");
      //while(fgets(buffer,255,input)!=NULL)
      //  printf("Parent: %s",buffer);
  }

  return 0;
}

最佳答案

父级需要向子级关闭其管道一侧,以便子级检测到文件结束并终止。

  while(fgets(buffer,255,stdin)!=NULL)
      fprintf(output,"%s",buffer);
  fclose(output); // does close(fd[1]);
  FILE *input = fdopen(fd2[0],"r");
  while(fgets(buffer,255,input)!=NULL)
    printf("Parent: %s",buffer);

关于C中通过管道进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34910707/

相关文章:

swift - 如何在 swift 中修改 shell 环境变量?

c++ - boost:如何按名称查找进程的进程ID?

memory - 低级编程: How to find data in a memory of another running process?

当写入器速度快于读取器时,C FIFO 崩溃

c - 使用 _Generic 进行 printf 格式化

c++ - 为什么这个嵌套 printf 语句打印 "5 53"?

linux - "less"命令如何获取标准输入?

shell脚本: Use a pipe as an input for tar

c - 在 C 中与系统调用同步

计算频谱分析仪的值