C-Execvp() always fails

时间:2016-10-20 19:02:59

标签: c exec

i'm trying to make a shell in c and currently trying the ls command but the child always returns that execvp couldn't work. here is the function.first i get the path i'm in and the command i get from stdin using exec that is why i remove the newline after that i duplicate the command and using strtok(delimiter is " ") i put all the arguments in an array for execv and 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 the execv never works and it returns the fprintf

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");
    }

}

1 个答案:

答案 0 :(得分:0)

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

Then that is the problem. If you read an exec manual page it will tell you that the first argument is the command that you should execute.

So to execute ls -l with execvp you should do e.g.

char *w_cmd[] = { "ls", "-l", NULL };
execvp(w_cmd[0], w_cmd);