gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:00:23 24 4
gpt4 key购买 nike

我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com