首页 > 解决方案 > 调用 execvp 两次会导致第二个 execvp 使用第一个 execvp 的参数

问题描述

我有一个非常奇怪的错误,我不知道为什么会这样,我正在尝试创建一个 shell,如果我想调用多个 execvp,它不起作用。如果我只传入 echo hello,它就可以工作,但是如果我有第一个 execvp 的 echo hello 和第二个 execvp 的 echo hello world,第二个 execvp 将打印“hello echo hello world”。


    void testexecute(char** arglist){
    int k;
    int status=0;
    pid_t child_pid;
    child_pid=fork();
    cout<<"This is our child_pid number "<<child_pid<<endl;
        if (child_pid == -1){
            // error, failed to fork()
        }
        else if (child_pid > 0){
            int status;
            waitpid(child_pid, &status, 0);
            cout<<"Our status here be "<<status<<endl;
            return status;
        }
        else {
            // we are the child
            if(execvp(arglist[0],arglist)==-1)
            {
                    _exit(EXIT_FAILURE);   // exec never returns
            }
            else
            {
                cout<<"Second else has reached "<<endl;
                exit(0);
            }
        }
    }

int main() { 
    char *argv[] = {"echo","testing","these","functions"};
    char *argvlist2[]= {"echo"," testssss","1","2"};
    testexecute(argvlist2);
    testexecute(argv);
    return 0;
}

当我运行此代码时,这是我的输出

testssss 1 2
testing these functions echo  testssss 1 2

我尝试检查 testexecute 中参数的内容,它传入了正确的参数,所以我不知道为什么它还将前一个参数传入 execvp()。

标签: c++shell

解决方案


推荐阅读