C语言 使用 dup2 进行管道

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3642732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:22:28  来源:igfitidea点击:

Using dup2 for piping

clinuxdup2

提问by Rob Kearnes

How do I use dup2 to perform the following command?

如何使用 dup2 执行以下命令?

ls -al | grep alpha | more

回答by theprole

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.

前两个命令的一个小例子。您需要使用 pipe() 函数创建一个管道,该管道将在 ls 和 grep 之间以及 grep 和更多之间的其他管道之间进行。dup2 所做的是将一个文件描述符复制到另一个文件描述符中。管道的工作原理是将 fd[0] 的输入连接到 fd[1] 的输出。您应该阅读 pipe 和 dup2 的手册页。如果您有其他疑问,我稍后可能会尝试简化示例。

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#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;
}

回答by Ignacio Vazquez-Abrams

You would use pipe(2,3p)as well. Create the pipe, fork, duplicate the appropriate end of the pipe onto FD 0 or FD 1 of the child, then exec.

你也会用pipe(2,3p)。创建管道,分叉,将管道的适当末端复制到孩子的 FD 0 或 FD 1 上,然后执行。