C-Execvp() always fails

i'm trying to make a shell in c and currently trying the ls command but the child always returns thatexecvpcouldn't work. here is the function.first i get the path i'm in and the command i get fromstdinusing exec that is why i remove the newline after that i duplicate the command and usingstrtok(delimiter is " ") i put all the arguments in an array forexecvand the "close it" with a null terminating string after that i print the elements of the array which give correct output ex(ls -l give ls "newline" -l) and then i print the path who also gives correctl output (/home/usr_name/Desktop). But theexecvnever works and it returns thefprintf

void ls(char* path,char* cmd){
    int pid,elements,l,i=0;;
    l=strlen(cmd);
    if(cmd[l-1]=='\n'){
        cmd[l-1]='\0';
    }
    char* ccmd=strdup(cmd);         
    char* t_cmd;
    char* w_cmd[1024];
    t_cmd=strtok(ccmd,DELIM);
    while(t_cmd!=NULL){
        w_cmd[i]=t_cmd;
        t_cmd=strtok(NULL,DELIM);
        i++;
    }
    w_cmd[i]='\0';
    elements=i;
    for(i=0;i<elements;i++){
        printf("%s\n",w_cmd[i] );
    }
    printf("%s\n",path);
    pid=fork();
    if(pid==0){
        execvp(path,w_cmd);
        fprintf(stderr, "Child process could not do execvp\n");
    }
    else{
        wait(NULL);
        printf("Child exited\n");
    }

}

You say thatpathis equal to"/home/usr_name/Desktop"(with your real user name of course)?

Then that is the problem. If youread anexecmanual pageit will tell you that the first argument is thecommandthat you should execute.

So to executels -lwithexecvpyou should do e.g.

char *w_cmd[] = { "ls", "-l", NULL };
execvp(w_cmd[0], w_cmd);
Tags: exec
What Others Are Reading