简体   繁体   中英

Execvp() is not accepting 'ls' as Argument

 #include <string.h>
 #include <stdio.h>
 #include <unistd.h>
 #define MAX_LIMIT 20 
 int main () {


printf("Shell> ");

    char str1[MAX_LIMIT]; 
    fgets(str1, MAX_LIMIT, stdin);    
    char delim[] =" ";
    char *parsed;
    int index = 0;
    char *cmd[index];

    parsed = strtok(str1,delim);    
    while( parsed != NULL) {
        cmd[index] = parsed;
        index++;        
        parsed = strtok(NULL, delim); 
     }   
    cmd[index] = NULL;
    int wow = fork();
    if(wow == 0){   
      execvp((char*)cmd[0],cmd);            
        }
    return(0);
    }

Everything above is working fine except execvp() cmd[0] receives string 'ls', technically execvp() should display the list but it doesn't. If I replace cmd[0] with 'ls', it works.

You have two main issues here.

First when you declare your array as char *cmd[index]; , the size of the array is not tied to current value of index as index changes. It sets the size to the current value of index which is 0. Creating an array of size 0 invokes undefined behavior . You need to set a fixed size for the array that will be big enough for your needs.

char *cmd[MAX_LIMIT];

The other problem is your choice of delimiters. The fgets function reads a line of text including the newline at the end of the input . So whichever parameter is read last will have a \\n at the end of it. To fix this, add \\n to the delimiter list.

char delim[] =" \n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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