我正在用C++編寫一個簡單的shell程序。當我將參數傳遞給execvp時,特別是對於ls
命令,我收到ls: cannot access H��p����: Protocol error
。其他命令也會出現類似的錯誤。C++函數調用execvp返回無法訪問C++ Shell程序中的錯誤
我的策略是解析輸入到vector<vector<char>
然後將其轉換爲char **
。
這裏是下面的轉換代碼:
//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;
然後,我通過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);
}
我編譯具有鐺++和上一個Debian 8的代碼虛擬機在Mac OS X.有沒有人知道最新進展?
你知道,普通的輸入運算符'>>'在空間上分開,並且在讀取字符串時會丟棄前導空間嗎?這意味着您的標記循環可以簡單地爲'while(ss >> s){...}'。 –
另外,你寫出'args'數組的邊界(並注意[可變長度數組](https://en.wikipedia.org/wiki/Variable-length_array)不是C++的一部分)。我沒有首先看到嵌套向量的原因,只是使用'std :: string'的向量,然後使用'const char *'的向量,並且不要讓' std :: string'出界(這可能是你的問題)!只有在實際需要時,即在「exec」調用之前,才轉換爲「const char *」的向量。 –
嗨,感謝您的快速響應!我使用嵌套向量是因爲我不知道我的參數長度或每個單獨的參數的長度,並且不想處理處理可變長度數組的開銷。考慮到這一點,它仍然是次優解決方案嗎? –