简体   繁体   English

C++ - 对 execvp 的函数调用返回无法访问 C++ Shell 程序中的错误

[英]C++ - Function Call To execvp Returns Cannot Access Error In C++ Shell Program

I am writing a simple shell program in C++.我正在用 C++ 编写一个简单的 shell 程序。 When I pass my arguments into execvp, in particular, for the ls command, I receive a ls: cannot access H p : Protocol error .当我将参数传递给 execvp 时,特别是对于ls命令,我收到ls: cannot access H p : Protocol error A similar error occurs for other commands as well.其他命令也会发生类似的错误。

My strategy is the parse the input into a vector<vector<char> and then convert it into a char ** .我的策略是将输入解析为vector<vector<char> ,然后将其转换为char **

Here is the conversion code below:下面是转换代码:

//input is parsed from command-line above
vector< vector<char> > args_vector;

string s;
stringstream ss(input);

while(getline(ss, s, ' ')){
    vector<char> cv(s.begin(), s.end());
    cv.push_back('\0');
    args_vector.push_back(cv);
}

char *args[args_vector.size() + 1];

for(int i = 0; i < args_vector.size(); i++){
    char *arg = &args_vector[i][0];   
    args[i] = arg;
}

args[args_vector.size() + 1] = NULL;

Then I pass args into execvp in the following code below:然后我在下面的代码中将 args 传递给 execvp:

pid_t child_pid
int status;
child_pid = fork();

if (child_pid == 0) {
    execvp(args[0], args);
    cout << "Error: execution of command failed";
}
else {
    pid_t pid;
    do {
        pid = wait(&status);
    } while (pid != child_pid);
}

I am compiling the code with clang++ and on a Debian 8 VM on Mac OS X. Does anyone have idea whats going?我正在使用 clang++ 和 Mac OS X 上的 Debian 8 VM 编译代码。有谁知道发生了什么?

To elaborate on my guess for your problem: I guess that the tokenizing (the first snippet of code) is in a separate function, and it then returns which makes the vector of vectors of characters you have be destructed, so the pointers you save in the args array will no longer be valid.详细说明我对您的问题的猜测:我猜标记化(代码的第一个片段)在一个单独的函数中,然后它返回,这使得您已经破坏了字符向量的向量,因此您保存的指针args数组将不再有效。 This leads to undefined behavior , and you are pretty lucky the program doesn't actually crash (which is a common symptom of undefined behavior).这会导致未定义行为,您很幸运,程序实际上并没有崩溃(这是未定义行为的常见症状)。

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

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