免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1184 | 回复: 3
打印 上一主题 下一主题

管道模拟出错 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-05-24 09:43 |只看该作者 |倒序浏览
比着书上说的写了一个管道模拟的小程序,运行完以后,屏幕就不回显输入的命令了。

  1. #include <stdio.h>
  2. #include <unistd.h>

  3. int main()
  4. {
  5.         int fd[2];
  6.         int pid;

  7.         if (pipe(fd) < 0)
  8.                 printf("pipe error\n");

  9.         if ((pid = fork()) == 0) {
  10.                 dup2(fd[1], 1);
  11.                 close(fd[0]);
  12.                 close(fd[1]);
  13.                 system("ls");
  14.                 return 0;
  15.         }
  16.         if ((pid = fork()) == 0) {
  17.                 dup2(fd[0], 0);
  18.                 close(fd[0]);
  19.                 close(fd[1]);
  20.                 system("more");
  21.                 return 0;
  22.         }
  23.         close(fd[0]);
  24.         close(fd[1]);
  25.         return 0;
  26. }
复制代码

开始怀疑是描述符乱套了,但保存原描述符后再恢复也没能起到作用,各位大虾给看看,谢谢!

论坛徽章:
1
荣誉版主
日期:2011-11-23 16:44:17
2 [报告]
发表于 2006-05-24 10:02 |只看该作者

  1. #include <stdio.h>
  2. #include <unistd.h>

  3. int main()
  4. {
  5.         int fd[2];
  6.         int pid;

  7.         if (pipe(fd) < 0)
  8.                 printf("pipe error\n");

  9.         if ((pid = fork()) == 0) {
  10.                 dup2(fd[1], 1);
  11.                 close(fd[0]);
  12.                 close(fd[1]);
  13.                 system("ls");
  14.                 return 0;
  15.         }
  16.         //if ((pid = fork()) == 0) {
  17.                 dup2(fd[0], 0);
  18.                 close(fd[0]);
  19.                 close(fd[1]);
  20.                 system("more");
  21.          //       return 0;
  22.         //}
  23.         close(fd[0]);
  24.         close(fd[1]);
  25.         return 0;
  26. }
复制代码


这样就好了,具体原因我也不清楚,
不过肯定是描述符乱套了。

论坛徽章:
0
3 [报告]
发表于 2006-05-24 14:47 |只看该作者
果然如斑竹所言正常运行了!修改后应该是父子进程之间建立的管道,不是两子进程之间的管道,我再仔细看看书上怎么说的。

论坛徽章:
0
4 [报告]
发表于 2006-05-24 15:26 |只看该作者
传统上,两个不相关进程之间不能使用无名管道进行通讯,
两个进程的话,可以考虑用有名管道。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP