web-dev-qa-db-ja.com

配管にdup2を使用する

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

ls -al | grep alpha | more
19
Rob Kearnes

最初の2つのコマンドの小さな例。 lsとgrepの間、およびgrepとmoreの間の他のパイプの間を移動するpipe()関数を使用してパイプを作成する必要があります。 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;
}
30
theprole

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