I am writing a simple shell program in C++. When I pass my arguments into execvp, in particular, for the ls
command, I receive a 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 **
.
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:
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?