如何在 C++ 中实现来自 linux shell 的管道命令?

how to implement pipe command from linux shell in c++?

我正在一个项目中工作以实现一个迷你 linux shell , 我想实现一个管道命令,它基本上是这样工作的: command1 | command2:使用管道字符“|”将产生一个管道,将 command1 stdout 重定向到它的写通道,将 command2 stdin 重定向到它的读通道。

或:

command1 |& command2:使用管道字符“|&”将产生一个管道,将 command1 stderr 重定向到管道的写入通道,将 command2 stdin 重定向到管道的读取通道。

现在命令 1 可以是来自 linux 的外部命令,我 运行 使用 execv 或我编写的内置命令,而命令 2 始终是外部命令

我的代码无法正常工作,我不知道问题到底出在哪里,因为我实现了很多命令,它们都运行良好,例如(cp、重定向...),所以基础很好我的代码,但是管道错了!例如,如果命令是:showpid | ./parser.exe 1 其中 parser.exe 是一个对命令进行解析的给定文件,例如此处如果 showpid 打印:shell process pid is 12311,则调用此命令 showpid | ./parser.exe 1 输出应为 "shell",但是在我的代码中,输出是 shell process pid is 12311

这是我的管道命令实现:

这是管道命令的 class :

class PipeCommand : public Command {
private:
    int pipeNum;
    int split;
    string cmd1;
    string cmd2;
public:
    PipeCommand(const char* cmd_line);
    virtual ~PipeCommand() {}
    void execute() override;
};

// the pipe constructor , here i want to extract each command from the right and left side of the pipe from the cmd_line , which  is the command line that i get
// fro example : " showpid | grep 1 "

PipeCommand::PipeCommand(const char* cmd_line):Command(cmd_line) {
    pipeNum = -1;
    isBackground = _isBackgroundComamnd(cmd_line);
    string cmd1 = "", cmd2 = "";
    int split = -1;
    for (int i = 0; i < this->num_args; i++) {
        if (strcmp(args[i], "|") == 0) {
            split = i;
            pipeNum = 1;

            break;
        }

        if (strcmp(args[i], "|&") == 0) {
            split = i;
            pipeNum = 2;
            break;
        }

    }


    for (int i = 0; i < split; i++) {
        cmd1 = cmd1 + args[i] + " ";
    }

    for (int i = split + 1; i < num_args; i++) {
        cmd2 = cmd2 + args[i] + " ";
    }


// the implementation of the pipe command
void PipeCommand::execute() {

    int pipeFd[2];
    int pid;
    pipe(pipeFd);

    pid = fork();
    if (pid == 0) { // child process .

    close(pipeFd[1]);
    dup2(pipeFd[1], pipeNum);


        if (isBuiltInCMD(args[0])) {   // if the command is built in which means i wrote it i run it like this ( this works fine i checked it)
            Command *newCmd = CreateBuiltInCommand(const_cast<char *>(cmd1.c_str()));
            newCmd->execute();
            exit(0);
        } else { // if the command is external than use execv
            const char **argv = new const char *[4];
            argv[0] = "/bin/bash";
            argv[1] = "-c";
            argv[2] = cmd1.c_str();
            argv[3] = nullptr;
            execv(argv[0], const_cast<char **>(argv));
            perror("execvp failed");

        } 
    } else {     // the parent process , basically runs the command2 , which it can be only an external command
        pid = fork();  // we fork again in the parent process

        if (pid == 0)  {      // the child process executes the secomd command using execv

            dup2(pipeFd[0], STDIN_FILENO);


        close(pipeFd[0]); 
        dup2(pipeFd[0], pipeNum); 

            // execute

                const char **argv = new const char *[4];
                argv[0] = "/bin/bash";
                argv[1] = "-c";
                argv[2] = cmd2.c_str();
                argv[3] = nullptr;
                execv(argv[0], const_cast<char **>(argv));
                perror("execvp failed");
                             
        } else {   // the parent process waits 

            waitpid(pid,NULL,0);
            close(pipeFd[1]);
            close(pipeFd[0]);
        }

    }
}

我认为您应该查看关闭/复制文件描述符的顺序。具体来说:

第一个命令需要使用现有的标准输入 (fd 0)。不要关闭它。 但是您应该关闭现有的 stdout (fd 1) 然后执行 fd dup 使其变为 1.

第二个命令以相反的方式执行。

我会用一个更简单的例子来测试。让管道工作,然后执行 exec。


这是编辑后添加的信息。

在 C/C++ 世界中,程序启动时有 3 个标准文件:

FD 0 是标准输入——用于输入 FD 1 是标准输出——用于正常输出 FD 2 是 stderr -- 用于错误输出

当你这样做时:

grep foo < file.txt | grep 栏

shell 的作用是:

-管道调用是否获取输入输出文件 - 在 foo 的第一个 grep 上,关闭 fd 0 (stdin) 并打开 file.txt 进行输入。它将落在 0 上,因此是 grep 命令的标准输入。 -关闭标准输出并将其分配给管道的输出部分

在第二个 grep 上:

-关闭 1(标准输入) - 并将管道输入部分移至 1,以便设置标准输入。

因此,最后:

part 1 fd 0 (stdin) 是文件 part 1 fd 1 (stdout) 是管道的输出部分 part 2 fd 0 (stdin) 是管道的输入部分