c - 从带有 fork() 的 exit() 返回是奇怪的移位

标签 c fork exit-code

我在 C 中有一个代码,它有时会自行 fork ,每个 fork 都会做一些事情然后返回一个错误代码。目前,每个子进程返回其 ID (0..n)。

void other(int numero){
    ...
    exit(numero);
}

int main(...){
    for(int i = 0; i < 6; i++){
        if(fork() == 0){
            other(i);
        }
    }
    int order[6];
    for(int i = 0; i < 6; i++){
        int code;
        waitpid(0, &code, 0);
        order[i] = code; // <-- HERE
    }
}

奇怪的是,这会返回实际值的倍数。通过替换我标记的行:

order[i] = code >> 8;

我设法得到了 0..5 的预期结果。但是,我真的不明白为什么会这样。我预计这是因为某种类型的问题,但我没有看到,我一直在使用整数。

最佳答案

order[i] = code; 的正确替换是 order[i] = WEXITSTATUS(code); 另外,请注意 waitpid 即使进程没有退出也可以返回;你应该使用 WIFEXITED 来确保它确实如此。

来自 man 2 waitpid :

   If wstatus is not NULL, wait() and waitpid() store status information
   in the int to which it points.  This integer can be inspected with
   the following macros (which take the integer itself as an argument,
   not a pointer to it, as is done in wait() and waitpid()!):

    WEXITSTATUS(wstatus)
          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.

您应该使用那里列出的各种宏,例如在您的情况下的 WEXITSTATUS 来理解 wstatus。除了使用它们之外,只有将 wstatus 视为不透明的 blob 才是安全的(除了它为 0 的特殊情况)。

关于c - 从带有 fork() 的 exit() 返回是奇怪的移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53035623/

相关文章:

mysql_real_escape_string() 导致段错误

c - 这段代码有什么问题?

后跟 exec 时的克隆、 fork 、vfork 行为

c++ - 如何在 Linux 中找到具有写时复制的 fork 进程之间共享多少内存?

c - C 中的哲学家就餐使用 fork()

perl - 如何在 Perl 中捕获输出和退出代码时执行外部脚本?

java - 如何在Windows批处理文件中获取Java程序的退出状态

c - 在推送/弹出其他寄存器时从堆栈访问相对于 EBP 的函数参数?

更改 waitpid() 的参数

boost::thread 退出代码?