c++ - I am to create a simple Command Interpreter that allows user to input commands like in any command line, but error occurs after 2 arguments -
command line / output
enter command: mkdir 1 enter command: touch one/file one/other one/more error: bad address enter command: ^z
c++ source code
int main(int argc, char *argv[]){ int rs; int count = 0; pid_t pid; char input[100]; char* temp; char* arg[6] = { (char*)0, (char*)0, (char*)0, (char*)0, (char*)0, (char*)0 }; //command arg1 arg2 arg3 arg4 null while(true){ cout << "enter command: "; cin.getline(input, 100); for( temp = strtok(input, " "); temp; temp = strtok(null, " ") ) { arg[count++] = temp; } pid = fork(); if(pid == -1){ perror("error"); exit(exit_failure); } if(pid == 0){ /*child process*/ /*if(count < 2){ rs = execlp(arg[0],arg[0],arg[1],null); cout << "arg[0]: " << arg[0] << "arg[1]: " << arg[1] << endl; } else if(count < 3){ rs = execlp(arg[0],arg[0],arg[1],arg[2],null); cout << "arg[0]: " << arg[0] << "arg[1]: " << arg[1] << "arg[2]: " << arg[2] << endl; } else if(count < 4){ rs = execlp(arg[0],arg[0],arg[1],arg[2],arg[3],null); cout << "arg[0]: " << arg[0] << "arg[1]: " << arg[1] << "arg[2]: " << arg[2] << "arg[3]: " << arg[3] << endl; } else if(count < 5){ rs = execlp(arg[0],arg[0],arg[1],arg[2],arg[3],arg[4],null); cout << "arg[0]: " << arg[0] << "arg[1]: " << arg[1] << "arg[2]: " << arg[2] << "arg[3]: " << arg[3] << "arg[4]: " << arg[4] << endl; }*/ rs = execvp(arg[0],arg); if(rs == -1){ perror("error"); exit(exit_failure); } } else{ /*parent process*/ wait(null); } }//end-while }//end program
you can see commented if-else statements trying different route, did not @ all.i assume problem using execvp not understand why. appreciate feedback.
arg[count++]
you need reset count
0
after executing each command.
Comments
Post a Comment