免费注册 查看新帖 |

Chinaunix

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

linux管道通信实验的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-05-07 21:22 |只看该作者 |倒序浏览
有这样一段实验程序:
#include<stdio.h>
#include<unistd.h>
#include<signal.h>
main()
{
    int p1,p2,fd[2];
    char outpipe[50];
    char inpipe1[50]="Child1 is sending a message to parent!";
    char inpipe2[50]="Child2 is sending a messege to parent!";
    pipe(fd);
   
    while((p1=fork())==-1);
    if (p1==0)
        {
           lockf(fd[1],1,0);
           write(fd[1],inpipe1,50);
           exit(0);
        }
    else
        {
        while((p2=fork())==-1);
        if (p2==0)
                {
            lockf(fd[1],1,0);
            write(fd[1],inpipe2,50);
            exit(0);
                }
        else
                {
            wait(0);
            read(fd[0],outpipe,50);
            lockf(fd[1],0,0);
            printf("Parent has received first message:\n");
            printf("%s\n",outpipe);
            wait(0);
            read(fd[0],outpipe,50);
            lockf(fd[1],0,0);
            printf("Parent has received second message:\n");
            printf("%s\n",outpipe);
            exit(0);
                }
        }
}


实验结果应该是:
parent has received first message:
child1 is sending a message to parent!
parent has received second message:
child2 is sending a message to parent!

可是我按照上面的程序编译执行后,出来下图这样结果(上面正确结果的后面二行没有显示出来),我反复找了几遍,也不知道我错在哪里,恳请各位DX指点,谢谢!



上图的那个黑方块一直在闪烁。我只有按CTRL+C强行终止。

论坛徽章:
0
2 [报告]
发表于 2009-05-08 09:11 |只看该作者
gcc version 4.1.2 20071124 (Red Hat 4.1.2-42)
编译运行和预期结果一样

论坛徽章:
0
3 [报告]
发表于 2009-05-09 08:36 |只看该作者
你猜一下,这样得到是是3个进程还是4个进程呢?

论坛徽章:
0
4 [报告]
发表于 2009-05-09 12:36 |只看该作者
3个吧
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP