繁体   English   中英

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

[英]How do I get my pipe command to accept options?

我正在为一个类编写外壳程序,并且需要实现管道。 现在,我的代码仅在第一个命令不使用参数时才有效。 例如:'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;
}

找到了。 在第一个孩子中,我给execvp错误的参数。 它必须是

execvp(cmd2c[0], cmd2c);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM