noname95 noname95 - 1 month ago 4
C Question

C-Execvp() always fails

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

}

Answer

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