奇怪的 显示结果(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)