天天看點

利用管道實作Linux ls| wc-l指令

#include<iostream>
#include<unistd.h>
#include<stdlib.h>
#include <sys/types.h>
int main()
{
        int fd[2]{};
        int nret=pipe(fd);
        pid_t pid=fork();
        if(pid==-1)
                perror("fork faild!");
        else if(pid==0)
        {
                close(fd[0]);
                dup2(fd[1],STDOUT_FILENO);
                int n=execlp("ls","ls",NULL);
                if(n==-1)
                {
                         perror("execlp faild!");
                         exit(1);
                }
        }
        else
        {
                close(fd[1]);
                dup2(fd[0],STDIN_FILENO);
                execlp("wc","wc","-l",NULL);
        }
}

           

繼續閱讀