用管道實現"ls | wc -l"命令

#include "./apue.h"  /*裏面包含一些需要的頭文件*/

int main(void){
        int fd[2];
        if(pipe(fd)==-1)
                err_exit("pipe error");
        pid_t pid;
        pid = fork();
        if(pid==-1)
                err_exit("fork error");
        if(pid==0){
                dup2(fd[1], STDOUT_FILENO);
                close(fd[0]);
                close(fd[1]);
                execlp("ls","ls",NULL);
                fprintf(stderr, "exec ls error\n");
                exit(EXIT_SUCCESS);
        }
        dup2(fd[0], STDIN_FILENO);
        close(fd[0]);
        close(fd[1]);
        execlp("wc","wc","-l",NULL);
        fprintf(stderr,"exec wc error\n");
        return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章