问题
I have the following code that forks a child and executes the command "a", which is an unknown command. However, execvp does not return an error and instead, "success" is printed. The same thing happens if I do "mv a b", when the file "a" does not exist. How should I capture and handle these errors?
int main ( int argc, char **argv ){
pid_t pid;
char *execArgs[] = { "a", NULL };
pid = fork();
// if fork fails
if (pid < 0){
exit(EXIT_FAILURE);
}
else if (pid == 0){
execvp(execArgs[0], execArgs);
if (errno == ENOENT)
_exit(-1);
_exit(-2);
}
else{
int status;
wait(&status);
if(!WIFEXITED(status)){
printf("error\n");
}
else{
printf("success\n");
}
}
}
回答1:
The program exited; it just exited with a non-zero status. The primary opposite of WIFEXITED
is WIFSIGNALED
— see the POSIX specification for wait() and WIFSTOPPED
and WIFCONTINUED
for the other options.
Use:
int corpse = wait(&status);
if (corpse != -1 && WIFEXITED(status))
{
int estat = WEXITSTATUS(status);
char *err = (estat == 0) ? "success" : "failure";
printf("PID %d exited with status %d (%s)\n", corpse, estat, err);
}
else
printf("PID %d didn't exit; it was signalled\n", corpse);
来源:https://stackoverflow.com/questions/26435219/execvp-doesnt-return-an-error-on-an-unknown-command