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

时间:2014-03-02 22:03:23

标签: 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;
}

1 个答案:

答案 0 :(得分:0)

找到它。在第一个孩子我给了execvp错误的论据。它必须是

execvp(cmd2c[0], cmd2c);