Using dup2 for piping

后端 未结 2 1903
执笔经年
执笔经年 2020-12-02 12:50

How do I use dup2 to perform the following command?

ls -al | grep alpha | more
2条回答
  •  星月不相逢
    2020-12-02 13:23

    A Little example with the first two commands. You need to create a pipe with the pipe() function that will go between ls and grep and other pipe between grep and more. What dup2 does is copy a file descriptor into another. Pipe works by connecting the input in fd[0] to the output of fd[1]. You should read the man pages of pipe and dup2. I may try and simplify the example later if you have some other doubts.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    #define READ_END 0
    #define WRITE_END 1
    
    int 
    main(int argc, char* argv[]) 
    {
        pid_t pid;
        int fd[2];
    
        pipe(fd);
        pid = fork();
    
        if(pid==0)
        {
            printf("i'm the child used for ls \n");
            dup2(fd[WRITE_END], STDOUT_FILENO);
            close(fd[WRITE_END]);
            execlp("ls", "ls", "-al", NULL);
        }
        else
        { 
            pid=fork();
    
            if(pid==0)
            {
                printf("i'm in the second child, which will be used to run grep\n");
                dup2(fd[READ_END], STDIN_FILENO);
                close(fd[READ_END]);
                execlp("grep", "grep", "alpha",NULL);
            }
        }
    
        return 0;
    }
    

提交回复
热议问题