c++ - 如何让我的管道命令接受选项?

标签 c++ linux

我正在为一个类编写 shell,我需要实现管道。现在,我的代码仅在第一个命令不使用参数时才有效。例如:'ls | wc -l' 有效,但 'ls -lt |头'没有。

void usePipe(string &command)
{
    int fd_pipe[2];
    int pid1;
    int pid2;
    int status;
    int wpid;
    string cmd1,cmd2;
    stringstream ss(command);
    vector<string> tok1,tok2;
    char **cmd1c;
    char **cmd2c;
    vector<const char*>args1,args2;

    pid1 = fork();
    if(pid1 == 0)
    {
        getline(ss,cmd1, '|');
        getline(ss,cmd2, '|');
        cmd1 = reduce(cmd1);
        cmd2 = reduce(cmd2);
        cout << cmd1 << "|" << endl;
        cout << cmd2 << "|" << endl;

        tok1 = split(cmd1,' ');
        tok2 = split(cmd2, ' ');
        for(int i = 0; i < tok1.size(); i++)
        {
            if(tok1.at(i).c_str()[0] != '\0')
            {
                args1.push_back(tok1.at(i).c_str());
                cout << "Pushed command: " << args1.back() << endl;
            }
        }
        args1.push_back(NULL);
        cmd1c =(char**) &args1[0];

        for(int i = 0; i < tok2.size(); i++)
        {
            if(tok2.at(i).c_str()[0] != '\0')
            {
                args2.push_back(tok2.at(i).c_str());
                cout << "Pushed command: " << args2.back() << endl;
            }
        }
        args2.push_back(NULL);
        cmd2c =(char**) &args2[0];

        pipe(fd_pipe);

        pid2 = fork();
        if(pid2 == 0)
        {
            cout << "in second child" <<endl;
            dup2(fd_pipe[1],1);
            close(fd_pipe[0]);
            close(fd_pipe[1]);
            execvp(cmd1c[0], cmd1c);
            perror("Exec Failed ");
            exit(5);
        }
        cout << "in first child"<< endl;
        dup2(fd_pipe[0],0);
        close(fd_pipe[0]);
        close(fd_pipe[1]);
        execvp(cmd2c[0], cmd1c);
        perror("Exec Failed ");
        exit(5);
    }
    wpid = wait(&status);
    cout << "Shell process "<< pid1 << " exited with status " << (status >> 8) <<  endl;
}

最佳答案

找到了。在第一个 child 中,我给了 execvp 错误的参数。它需要是

execvp(cmd2c[0], cmd2c);

关于c++ - 如何让我的管道命令接受选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22134185/

相关文章:

c++ - OpenGL纹理倒置

c++ - 将可变函数参数转发到 std::function 对象

c++ - 通过 vs code 远程调试 arm 板时 Pretty-printer 不工作

linux - Bash 数量限制?

c++ - 如何编写完全可移植的 4 字节字符常量的编译时初始化

c++ - Tic Tac Toe cin 输入问题

linux - bash 脚本中的错误替换错误

c - Linux 设备驱动程序中的事件代码 (EVIOCG*)

linux - Linux 内核中的 setscheduler()

python - gdb python模块找不到它自己的任何功能