Reputation: 798
int spawn( char* program, char** args) {
pid_t child_pid;
child_pid = fork();
if( child_pid > 0) { /
wait(NULL);
return (int)child_pid;
}
else {
if(execvp(program, args) == -1){
exit(EXIT_FAILURE);
}
return (int)child_pid;
}
}
I know this code is kind of messy but please bear with me: I'm trying to create my own shell. This is the function that will spin up a new child process and execute the code. However, I am unable to return an error when I type in a string.
For example, if I type 'heyman' I just get 'heyman' back while I'd like to get some sort of error ('heyman' is not a command) back.
I was hoping the exit(EXIT_FAILURE) would do that but it has not. Would appreciate if anyone could help me here
Upvotes: 0
Views: 563
Reputation: 780769
Use perror()
to report the error.
if (execvp(program, args) == -1) {
perror("execvp");
exit(EXIT_FAILURE);
}
There's no need to use return (int)child_pid
in the child function. If execvp()
succeeds, none of the code after it runs; if it fails, you report the error and exit.
Upvotes: 3