Forked child exits with -1, but WEXITSTATUS gets 255

拜拜、爱过 提交于 2019-12-12 04:36:20

问题


I exit with -1 in the child, but the parent picks up 255 instead. Is there a way to make the parent recognize -1 instead? Here is my code

  pid = fork();

  // if fork fails
  if (pid < 0){
    exit(EXIT_FAILURE);
  }
  else if (pid == 0){
    // purposely exit
    _exit(-1);
  }
  else{
    int status;
    int corpse = wait(&status);
    if (WIFEXITED(status))
    {
      int estat = WEXITSTATUS(status);
      if (estat == 0){
        printf("Command was successfully executed\n");
      }
      else{
        printf("Error: child exited with status %d\n", estat);
      }
    }
    else
      printf("signalled\n", corpse);

回答1:


From wait:

WEXITSTATUS(status)

returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) or as the argument for a return statement in main(). This macro should be employed only if WIFEXITED returned true.

The least significant 8 bits of -1 is 0xFF(255).




回答2:


the status returned from function wait contains information of not only the exit code of the child process, but also contains the termination reason, etc.. thus, it is impossible to get the exact exit code of the child process, and only the least 8 bits of the child exiting code is represented.




回答3:


status will be 0xFF00 after wait().



来源:https://stackoverflow.com/questions/26435730/forked-child-exits-with-1-but-wexitstatus-gets-255

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