C语言 为什么 wait() 将状态设置为 256 而不是分叉进程的 -1 退出状态?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3659616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does wait() set status to 256 instead of the -1 exit status of the forked process?
提问by Jonathan Leffler
I'm trying to return an integer value from a child process.
我正在尝试从子进程返回一个整数值。
However, if I use exit(1)i get 256as the output. exit(-1)gives 65280.
但是,如果我使用exit(1)我得到256作为输出。exit(-1)给出65280。
Is there a way I can get the actual int value that I send from the child process?
有没有办法可以获得我从子进程发送的实际 int 值?
if(!(pid=fork()))
{
exit(1);
}
waitpid(pid,&status,0);
printf("%d",status);
Edit:Using exit(-1) (which is what I actually want) I am getting 255 as the output for WEXITSTATUS(status). Is it supposed to be unsigned?
编辑:使用 exit(-1) (这是我真正想要的)我得到 255 作为 WEXITSTATUS(status) 的输出。它应该是未签名的吗?
回答by Darron
Have you tried "man waitpid"?
你试过“man waitpid”吗?
The value returned from the waitpid() call is an encoding of the exit value. There are a set of macros that will provide the original exit value. Or you can try right shifting the value by 8 bits, if you don't care about portability.
从 waitpid() 调用返回的值是退出值的编码。有一组宏将提供原始退出值。或者,如果您不关心可移植性,您可以尝试将值右移 8 位。
The portable version of your code would be:
您的代码的可移植版本将是:
if(!(pid=fork()))
{
exit(1);
}
waitpid(pid,&status,0);
if (WIFEXITED(status)) {
printf("%d", WEXITSTATUS(status));
}
回答by Jonathan Leffler
The exit code is a 16-bit value.
退出代码是一个 16 位值。
The high-order 8 bits are the exit code from exit().
高 8 位是从 的退出代码exit()。
The low-order 8 bits are zero if the process exited normally, or encode the signal number that killed the process, and whether it dumped core or not (and if it was signalled, the high-order bits are zero).
如果进程正常退出,低位 8 位为零,或者对杀死进程的信号编号进行编码,以及是否转储核心(如果已发出信号,则高位为零)。
Check out the <sys/wait.h>header and the documentation for the waitpid()system call to see how to get the correct values with WIFEXITED and WEXITSTATUS.
查看系统调用的<sys/wait.h>标头和文档,waitpid()了解如何使用 WIFEXITED 和 WEXITSTATUS 获取正确的值。
回答by Matthew Flaschen
See the documentation. First use WIFEXITEDto determine whether it terminated normally (possibly with non-zero status). Then, use WEXITSTATUSto determine what the low-order 8 bits of the actual status are.
请参阅文档。首先用于WIFEXITED判断是否正常终止(可能是非零状态)。然后,WEXITSTATUS用以确定实际状态的低8位是什么。
回答by user4762317
Use WEXITSTATUS()to read the correct exit status of child
使用WEXITSTATUS()读孩子的正确退出状态
Pass the status returned by waitpid()or wait()
传递waitpid()或返回的状态wait()
e.g.:
例如:
int cstatus;
wait(&cstatus);
printf("Child exit status : %d\n", WEXITSTATUS(cstatus));
回答by user207421
It doesn't. It sets it to 255. There are only 8 bits available. See the documentation.
它没有。它将它设置为 255。只有 8 位可用。请参阅文档。

