#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #define MAXLINE 100 char buf[MAXLINE]; int main(int argc, char** agrv) { int pipefd[2]; int ret; if(0 != pipe(pipefd))//创建管道 { perror("pipe\n"); exit(1); } //创建子程序 if((ret=fork()) < 0)//创建失败 { perror("fork\n"); exit(1); } else if(ret == 0)//子程序 { FILE* fp; close(pipefd[0]);//关闭管道可读端 fp = fopen("./main.c","r"); //打开已存在可读文件 if(NULL == fp) { perror("fopen\n"); exit(1); } while(fgets(buf,MAXLINE,fp) != NULL)//将文件内容全部读入管道 { int n = strlen(buf); if(n != write(pipefd[1],buf,n)) { perror("write\n"); exit(1); } }//end while if(ferror(fp))//在读的过程文件是否有报错 { perror("ferror\n"); exit(1); } close(pipefd[1]);//关闭文件可写端 exit(0);//退出子程序 } else { close(pipefd[1]);//关闭管道可写端 if(-1 == wait(NULL))//等待子程序完全将文件内容读入到管道 { perror("wait\n"); exit(1); } if(dup2(pipefd[0],STDIN_FILENO) != STDIN_FILENO)//重新设置标准输入为管道可读端 { perror("dup2\n"); exit(1); } if(execl("/bin/more","more",(char*)0) < 0 )//分页程序 自动调用标准输入文件 显示管道内容 { perror("execl\n"); exit(1); } } return 0; }
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。