Reputation: 179
I try to pass command line argument "ls -l /user/myuser" in my terminal and execute execvp in my main.
But somehow it gives me this error when i am debugging the code.
int main(int argc, char *argv[]){
pid_t pid;
pid = fork();
//negative value is failed, 0 is newly created child process
if(pid < 0){
fprintf(stderr, "Fork Failed");
exit(-1);
}else if(pid == 0){
//fork() -> child process
printf("You entered %d commands: \n", argc);
argv[argc + 1] = NULL;
execvp(argv[0],argv);
}else{
wait(NULL);
printf("child complete\n");
exit(0);
}
return 0;
}
Upvotes: 0
Views: 182
Reputation: 3879
argv[0]
is your executable, you need to pass the second argument in this case. Also don't do argv[argc + 1] = NULL;
since the C standard says that argv is NULL terminated.
This should work:
int main(int argc, char *argv[]){
pid_t pid;
pid = fork();
//negative value is failed, 0 is newly created child process
if(pid < 0){
fprintf(stderr, "Fork Failed");
exit(-1);
}else if(pid == 0){
//fork() -> child process
printf("You entered %d commands: \n", argc);
execvp(argv[1],&argv[1]);
}else{
wait(NULL);
printf("child complete\n");
exit(0);
}
return 0;
}
Upvotes: 1