标题:奇怪的 显示结果(linux下c编程问题)
只看楼主
vfdff
Rank: 6Rank: 6
等 级:侠之大者
威 望:8
帖 子:2172
专家分:425
注 册:2005-7-15
结帖率:79.17%
 问题点数:0 回复次数:0 
奇怪的 显示结果(linux下c编程问题)
为什么使用 ./testPipe 直接把printf 内容输出到屏幕上 和
      使用 ./testPipe > aa.txt 把printf 输出内容重定向到文件aa.txt 中后,
使之与屏幕上的输出比较存在差异

而且,不管是屏幕上,还是文件aa.txt 中,他们的输出性数均超过代码中的printf 次数

附源代码:
// code for linux ,taking an example for pipe communication p88
#include <stdio.h>
#include <errno.h>
int main(int argc,int *argv[])
{
    int status;
    int pid[2];
    int pipe_fd[2];

    char *prog1_argv[4];
    char *prog2_argv[2];
   
    // creat table of parameters
    prog1_argv[0] = "/usr/local/bin/ls";
    prog1_argv[1] = "-1";
    prog1_argv[2] = "/";
    prog1_argv[3] = NULL;

    prog2_argv[0] = "/usr/local/bin/more";
    prog2_argv[1] = NULL;

    // creat pipe
    if (pipe(pipe_fd) < 0)
    {
        perror("pipe failed\n");
        exit(errno);
    }

    // creat process for cmd ls
    if ((pid[0]=fork()) < 0 )
    {
        perror("fork failed\n");
        exit(errno);
    }
   
    printf("Y\n");
     printf("yyY\n");
     printf("pipe_fd[0]=%d,pipe_fd[1]=%d\n",pipe_fd[0],pipe_fd[1]);
      printf("pid[0]=%d,pid[1]=%d\n",pid[0],pid[1]);
 
    if (!pid[0])
    {
        // copy the written description of the pipe to the standard output,then close
        printf("pipe_fd[0]=%d,pipe_fd[1]=%d\n",pipe_fd[0],pipe_fd[1]);
        close(pipe_fd[0]);
        printf("pipe_fd[0]=%d,pipe_fd[1]=%d\n",pipe_fd[0],pipe_fd[1]);
     dup2(pipe_fd[1],1);
         printf("pipe_fd[0]=%d,pipe_fd[1]=%d\n",pipe_fd[0],pipe_fd[1]);
        close(pipe_fd[1]);
        printf("pipe_fd[0]=%d,pipe_fd[1]=%d\n",pipe_fd[0],pipe_fd[1]);
        //execute  cmd ls
    printf("zhong");
        execvp(prog1_argv[0],prog1_argv);
        printf("why?0\n");
    }
    if (!pid[0]){}

    printf("z\n");

    if (pid[0])
    {
        // farther process
        // creat children process for cmd more
        if ((pid[1]=fork()) < 0 )
        {
            perror("fork failed\n");
            exit(errno);
        }

        if (!pid[1])
        {
            // children process
            // copy the read description of the pipe to the standard output,then close
            close(pipe_fd[1]);
            dup2(pipe_fd[0],0);
            close(pipe_fd[0]);
            //execute  cmd more
        printf("2.0\n");
            execvp(prog2_argv[0],prog2_argv);
            printf("2.1\n");
        }
        printf("3\n");
    }

    // farther process
    close(pipe_fd[0]);
    close(pipe_fd[1]);
   
    //waitid(pid[1],&status,0); // wait for process pid to exit
    printf("Done wating for more.\n");
}

linux下c编程问题.rar (153.85 KB)


testPipe.JPG (110.94 KB)
搜索更多相关主题的帖子: linux c编程 多进程 pipe fork 
2008-11-01 11:24



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-241830-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.443885 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved