问题描述
我有以下代码,它会分叉一个孩子并执行命令"a",这是一个未知命令.但是,execvp不会返回错误,而是显示成功".如果我执行"mv a b",而文件"a"不存在,也会发生相同的情况.我应该如何捕获和处理这些错误?
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");
}
}
}
推荐答案
程序已退出;它只是以非零状态退出. WIFEXITED
的主要反义词是 WIFSIGNALED
—请参阅 wait()
的POSIX规范.和 WIFSTOPPED
和 WIFCONTINUED
用于其他选项.
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.
使用:
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);
这篇关于Execvp不会在未知命令上返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!