20

dup2 を使用して次のコマンドを実行するにはどうすればよいですか?

ls -al | grep alpha | more
4

2 に答える 2

31

最初の2つのコマンドの小さな例。lsとgrepの間を行き来するpipe()関数と、grepとそれ以上の間の他のパイプを使ってパイプを作成する必要があります。dup2が行うことは、ファイル記述子を別の記述子にコピーすることです。パイプは、fd[0]の入力をfd[1]の出力に接続することによって機能します。pipeとdup2のmanページを読む必要があります。他に疑問がある場合は、後で例を簡略化してみます。

#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;
}
于 2010-09-04T16:55:59.890 に答える
2

あなたも使うでしょうpipe(2,3p)。パイプを作成し、フォークし、パイプの適切な端を子の FD 0 または FD 1 に複製してから、実行します。

于 2010-09-04T14:57:45.337 に答える