3

据我所知,如果 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.  
        }
4

2 回答 2

5

使用该选项时,WNOHANG希望大部分时间waitpid会返回-1,并errno设置为ECHILD.

无论如何,无论何时return ,您waitpid 都不-1应该查看childStatus,这(据我所知)可能只是垃圾。相反,请查看errno并适当地处理它。

否则,就目前而言,您的代码似乎没问题,并且您应该0能够EXIT_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");
   }

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

于 2014-04-04T16:13:12.353 回答
3

WIFEXITED 将读取存储在 childStatus 中的任何值,它只是一个整数,因此它不必来自 waitpid() - 试试例如

for(i = 0; i < 1234; i++)
        printf("WIFEXITED(%d) %s\n", i, WIFEXITED(i) ? "yes" : "no");

childSTatus 和 WIFEXITED(childStatus) 之间的区别有点棘手......基本上退出状态已被滥用来告诉退出状态杀死进程的信号:你想要类似的东西

struct exitstatus {
        int status;
        int signalnumber;
        enum { exited, signaled };
};

但是这些信息已以某种方式压缩成一个整数(我不确定是否在任何地方定义了确切的细节):例如,在我的计算机上,低 8 位用于信号编号(如果有)和位 8 -15 用于退出代码。任何地方的重要一点是,您不需要知道它是如何发生的,只需要知道如何通过 WIFEXITED 和朋友获得您想要的结果。

于 2014-04-04T15:44:05.430 回答