Execvp doesn't return an error on an unknown command

◇◆丶佛笑我妖孽 提交于 2021-01-28 11:11:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!