为什么 wait() 将分叉进程的状态设置为 255 而不是 -1 退出状态?
我试图从子进程返回一个整数值。
但是,如果我使用 exit(1)
,我会得到 256
作为 wait()
的输出。使用 exit(-1)
给出 65280
。
有没有办法获取从子进程发送的实际 int 值?
if(!(pid=fork()))
{
exit(1);
}
waitpid(pid,&status,0);
printf("%d",status);
编辑:使用exit(-1)
(这是我真正想要的)我得到255作为WEXITSTATUS(status)
的输出。应该是未签名的吧?
I'm trying to return an integer value from a child process.
However, if I use exit(1)
I get 256
as the output from wait()
. Using exit(-1)
gives 65280
.
Is there a way I can get the actual int value that I send from the child process?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你试过“man waitpid”吗?
从 waitpid() 调用返回的值是退出值的编码。有一组宏将提供原始退出值。或者,如果您不关心可移植性,您可以尝试将值右移 8 位。
您的代码的可移植版本将是:
Have you tried "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.
The portable version of your code would be:
退出代码是一个 16 位值。
高 8 位是
exit()
的退出代码。如果进程正常退出,则低位 8 位为零,或者编码杀死进程的信号编号,以及是否转储核心(如果已发出信号,则高位为零)。
查看
标头和waitpid()
系统调用,了解如何使用 WIFEXITED 和 WEXITSTATUS 获取正确的值。The exit code is a 16-bit value.
The high-order 8 bits are the exit code from
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).
Check out the
<sys/wait.h>
header and the documentation for thewaitpid()
system call to see how to get the correct values with WIFEXITED and WEXITSTATUS.请参阅文档。首先使用
WIFEXITED
来确定它是否正常终止(可能是非零状态)。然后,使用WEXITSTATUS
来确定实际状态的低8位是什么。See the documentation. First use
WIFEXITED
to determine whether it terminated normally (possibly with non-zero status). Then, useWEXITSTATUS
to determine what the low-order 8 bits of the actual status are.使用
WEXITSTATUS()
读取 child 的正确退出状态传递
waitpid()
或wait()
返回的状态,例如:
Use
WEXITSTATUS()
to read the correct exit status of childPass the status returned by
waitpid()
orwait()
e.g.:
事实并非如此。它将其设置为 255。只有 8 位可用。请参阅文档。
It doesn't. It sets it to 255. There are only 8 bits available. See the documentation.