Home > Software engineering >  execvp not executing commands given by user input
execvp not executing commands given by user input

Time:10-20

I am attempting to execute command lines given by user input but for some reason the execvp() function isn't executing the command. I read in a user input and split it, store it into an array and use the excevp() function to execute it. I even printed out the spots in the array to make sure it was placing the token into the right spot and it is. Here is my code in C

char b[100];
int i = 0;
char *token;
char *array[3];
printf("Please enter the command you want to use: ");
fgets(b, 100, stdin);
token = strtok (b, " ");
while (token != NULL){
    array[i  ] = token;
    printf("%s\n",token);
    token = strtok(NULL, " ");
}

printf("%s", array[0]);
printf("%s", array[1]);
execvp(array[0], array);

So for example if I were to type in "ls" into the command line in the program and hit enter it will just go to the next line and nothing will execute. Are there any recommendation to fix this because I am lost on where to begin?

CodePudding user response:

The problem is array[0] is ls\n (as fgets reads newline character as well) and not ls you have to remove \n as well.

You can simply create an array of delimiters like this:

char delimiters[] = " \t\n";

and then simply do

 token = strtok(b, delimiters); // Use delimiters instead of only " " (whitespace)
  while (token != NULL) {
    array[i  ] = token;
    printf("%s\n", token);
    token = strtok(NULL, delimiters); // Use delimiters instead of only " " (whitespace)
  }
  • Related