WEXITSTATUS(childStatus) 返回 0 但 waitpid 返回 -1

kap*_*dit 3 c linux waitpid wexitstatus

据我所知,如果 waitpid 返回 -1,则它是错误条件。如何从 WEXITSTATUS(childStatus) 中的子进程获得成功 (EXIT_SUCCUSS)?

waitpid 中的 childStatus 与 WEXITSTATUS(childStatus) 的返回值有什么区别?一样吗?

pid_t returnValue = waitpid(Checksum_pid, &childStatus, WNOHANG);
printf("return value = %d", returnValue);
printf("return value = %d", childStatus);

if (WIFEXITED(childStatus))
        {
            printf("Exit Code: _ WEXITSTATUS(childStatus)") ;    
            //Proceed with other calculation.  
        }
Run Code Online (Sandbox Code Playgroud)

Jos*_*sey 5

当使用选项WNOHANG,我会想到的是大部分的时间waitpid将返回-1,与errno设置为ECHILD

在任何情况下,只要waitpid -1,你不应该看childStatus,它(据我所知)可能只是垃圾。相反,请查看errno并适当处理它。

否则,你的代码似乎是去是好的,因为到目前为止,你应该能够提取0EXIT_SUCCESSchildStatus

的手册页waitpid建议了以下示例代码:

   if (WIFEXITED(status)) {
       printf("exited, status=%d\n", WEXITSTATUS(status));
   } else if (WIFSIGNALED(status)) {
       printf("killed by signal %d\n", WTERMSIG(status));
   } else if (WIFSTOPPED(status)) {
       printf("stopped by signal %d\n", WSTOPSIG(status));
   } else if (WIFCONTINUED(status)) {
       printf("continued\n");
   }
Run Code Online (Sandbox Code Playgroud)

尽管为此添加最后的else printf("oops?\n")声明可能是个好主意。