日期:2014-05-16 浏览次数:20632 次
#include <apue.h> #include <sys/wait.h> #define DEF_PAGER "/bin/more" int main(int argc,char * argv[]) { pid_t pid; char * argv0; char * pager; int n; FILE * fp; int fd[2]; char buffer[1024]; if(argc != 2) { printf("usage : ./15.6 pathname\n"); exit(0); } if((fp = fopen(argv[1],"r"))==NULL) { printf("can't open"); } if(pipe(fd)<0) { printf("pipe error\n"); } if((pid = fork())<0) { printf("fork error"); } else if(pid > 0) { close(fd[0]); while(fgets(buffer,sizeof(buffer),fp) != NULL) { n = strlen(buffer); if(write(fd[1],buffer,n)!=n) { printf("write error"); } } if(ferror(fp)) { printf("fgets error"); } close(fd[1]); sleep(1); if(waitpid(pid,NULL,0)<0) { printf("wait error"); } exit(0); } else { close(fd[1]); if(fd[0] != STDIN_FILENO) { if(dup2(fd[0],STDIN_FILENO) != STDIN_FILENO) { printf("duplicate error"); } close(fd[0]); } else { if((pager = getenv("PAGER"))==NULL) { pager = DEF_PAGER; } if((argv0 = strrchr(pager,'/'))!=NULL) { argv0++; } else argv0 = pager; if(execl(pager,argv0,(char *)0)<0) { printf("execute error\n"); } } } exit(0); }