1

私はc++で複数のパイプを実装しようとしています。つまり、たとえばls-l|の実行をシミュレートするプログラムを作成したいと思います。ヘッド-n10| wc-l。

コードはすべて正常に機能します。しかし、すべてのコマンドが正しく実行された後、コマンドラインに戻るにはEnterキーを押す必要があります。どこかで「wait()」する必要があると思います

これが私が今持っているコードです。

using namespace std; 
#include <stdio.h>
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(){

int pid;
int fd[4];

pipe(fd + 0); // pipe between the 1st and 2nd command
pipe(fd + 2); // pipe between the 2nd and 3rd command

for( int i = 0; i < 3; i++){ // 3 commands

    pid = fork();

    if(pid == 0){// child process

        if( i == 0 ){// first command

            char *arg[10];
            arg[0] = "ls";
            arg[1] = NULL;

            close(fd[0]);
            dup2(fd[1], 1);
            execvp(arg[0], arg);
        }
        else if( i == 1){// second command

            char *arg[10];
            arg[0] = "head";
            arg[1] = "-n1";
            arg[2] = NULL;

            dup2(fd[0], 0);
            dup2(fd[3], 1);
            execvp(arg[0], arg);
        }
        else if( i== 2){// third command

            char *arg[10];
            arg[0] = "wc";
            arg[1] = "-l";
            arg[2] = NULL;

            close(fd[3]);
            dup2(fd[2], 0);
            execvp(arg[0], arg);

        }

    }

    else{// parent
    }

}

}

私は私のようなすべての投稿を通過したと思いますが、それでもこれを理解することはできません。

誰か助けてもらえますか?

4

0 に答える 0