1

我正在尝试在 C++ 中实现多个管道。即,我想编写一个程序来模拟执行,例如 ls -l | 头-n 10 | 厕所-l。

代码一切正常。但是在所有命令都正确执行之后,我需要按回车键返回命令行。我想我必须在某个地方“等待()”

这是我现在拥有的代码。

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