免费注册 查看新帖 |

Chinaunix

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

[C] 求大神帮忙看看原因~~ [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-03-14 09:58 |只看该作者 |倒序浏览
源程序如下。
在pipeline中建立了管道,以及父子进程。在child1中的改读管道为0号描述符,在father1中改写管道为3号描述符。我在father1.c中先写的顺序是
        printf("parent!!!");
        sleep(2);
        write(3, string, len);//3号对应管道文件的写
        sleep(2);
        printf("parent!!!");
但为什么最终执行pipeline的结果却是:parent is using pipe write
child!!!parent!!!parent!!!
而不是parent!!!parent is using pipe write parent!!!
child!!!?
明明第一个printf("parent!!!");在前,然后写管道,最后又是printf("parent!!!");结果却是两个parent都在最后显示在终端上。

/*pipeline.c*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define STD_INPUT 0
#define STD_OUTPUT 1
void pipeline(char*, char*);
int fd[2];
void main()
{
        static char process1[] = "father1",process2[]="child1";
        pipe(fd);//建立管道
        pipeline(process1,process2);//调用函数
        exit(1);
}

void pipeline(char * pro1,char * pro2)
{
        int i;
        while((i = fork()) == -1);
        if(i)//父
        {
                close(fd[0]);
                close(3);//关闭3
                dup(fd[1]);//把写的管道文件描述符给3
                close(fd[1]);//关闭写的管道文件描述符
                execl(pro1,pro1,NULL);
                printf("-- father1 failed.\n");
        else//子
        {
                close(fd[1]);
                close(STD_INPUT);
                dup(fd[0]);
                close(fd[0]);
                execl(pro2,pro2,NULL);
                printf("child1 failed.\n");
        }
        exit(2);
}

/*father1.c*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void main()
{
        static char string[] = "parent is using pipe write";
        int len;
        len = sizeof(string);
        printf("parent!!!");
        sleep(2);
        write(3, string, len);//3号对应管道文件的写
        sleep(2);
        printf("parent!!!");
        exit(0);
}
/*child1.c*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int  main()
{
        char output[30];
        read(0,output,30);//0号描述符对应的是管道文件的读
        printf("%s \nchild!!!",output);//读完后会有显示child!!!
        return 0;
}
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP