使用dup2管道 [英] Using dup2 for piping

查看:113
本文介绍了使用dup2管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用dup2执行下面的命令?

  LS -al | grep的阿尔法|更多


解决方案

一个小例子与前两个命令。您需要创建一个管道与管道()函数,将grep和更多的LS和grep等管之间去。什么dup2做的就是复制一个文件描述符到另一个。管道工程通过FD [0]输入连接到FD [1]的输出。你应该阅读管dup2的手册页。我可能会尝试,后来简化的例子,如果你有一些其他的疑惑。

 的#include< SYS / types.h中>
#包括LT&;&unistd.h中GT;
#包括LT&;&stdio.h中GT;
#包括LT&;&string.h中GT;
#包括LT&;&errno.h中GT;#定义READ_END 0
#定义WRITE_END 1INT
主(INT ARGC,CHAR *的argv [])
{
    将为pid_t PID;
    INT FD [2];    管(FD);
    PID =叉();    如果(PID == 0)
    {
        的printf(我用LS \\ n孩子);
        dup2(FD [WRITE_END],STDOUT_FILENO);
        关闭(FD [WRITE_END]);
        execlp(LS,LS,-al,NULL);
    }
    其他
    {
        PID =叉();        如果(PID == 0)
        {
            的printf(我的第二个孩子,这将是用于运行的grep \\ n);
            dup2(FD [READ_END],STDIN_FILENO);
            关闭(FD [READ_END]);
            execlp(grep的,grep的,阿尔法,NULL);
        }
    }    返回0;
}

How do I use dup2 to perform the following command?

ls -al | grep alpha | more

解决方案

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

这篇关于使用dup2管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆