免费注册 查看新帖 |

Chinaunix

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

无名管道通信 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-04-06 18:06 |只看该作者 |倒序浏览
下面这段代码原来自于LINUX源码情景分析,敲进去,修改了下代码中的错误,运行倒是成功。
可结果却有些奇怪。这是我在Redhat Linux9.0里面执行的结果,何故两次输出的结果是不同的?

Red Hat Linux release 9 (Shrike)
Kernel 2.4.20-8 on an i686
login: root
Password:
Last login: Fri Apr 6 15:48:14 from 192.168.0.10
You have new mail.
[root@wollt root]# cd devel
[root@wollt devel]# gcc pipe.c
[root@wollt devel]# ./a.out
63 Done!
[root@wollt devel]# /bin/ls -l pipe.c | /usr/bin/wc -c
64
[root@wollt devel]#

默地想起前次把代码中args2中的参数pipe.c去掉时,输出结果如下:

[root@wollt devel]# ./a.out
1027 Done!
[root@wollt devel]# ls -l | wc -c
1044
[root@wollt devel]# ls -l | wc -l
17
[root@wollt devel]#

发现规律没?每一行多一,即63+1=64以及1027+17=1044,这是何故,这两次执行差异在哪?想不明白。于是乎再试:

[root@wollt devel]# echo abc | wc -c
4

晕了,这哪门子理哟。
Appendix:
#include stdio.h>
int main()
{
    int child_B, child_C;
    int pipefds[2];    /* pipefds[0] for read, pipefds[1] for write */
    char *args1[] = {"/usr/bin/wc", "-c", NULL};
    char *args2[] = {"/bin/ls", "-l", "pipe.c", NULL};
    /* process A */
    pipe(pipefds);    /* create a pipe */
    if (!(child_B = fork()))    /* for process B */
    {
        /**** Process B ****/
        close(pipefds[1]);    /* close the write end */
        /* redirect stdin */
        close(0);
        dup2(pipefds[0], 0);
        close(pipefds[0]);
        /* ecec the target */
        execve("/usr/bin/wc", args1, NULL);    /* no return if success */
        printf("pid %d: I am back, something is wrong!\n", getpid());
    }
    /* process A continues */
    close(pipefds[0]);    /* close the read end */
    if(!(child_C = fork()))    /* for process C */
    {
        /**** process C ****/
        /* redirect stdout */
        close(1);
        dup2(pipefds[1], 1);
        close(pipefds[1]);
        /* exec the target */
        execve("/bin/ls", args2, NULL);    /* no return if success */
        printf("pid %d: I am back, something is wrong!\n", getpid());
    }
    /* process A continues */
    close(pipefds[1]);    /* close the write end */
    wait4(child_B, NULL, 0, NULL);    /* wait for process B to finish */
    printf("Done!\n");
    return 0;
}


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/34376/showart_272328.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP