为什么wait()将状态设置为255,而不是分叉进程的-1退出状态? [英] Why does wait() set status to 255 instead of the -1 exit status of the forked process?
问题描述
我正在尝试从子进程中返回一个整数值.
I'm trying to return an integer value from a child process.
但是,如果我使用 exit(1)
,则会得到 256
作为 wait()
的输出.使用 exit(-1)
给出 65280
.
However, if I use exit(1)
I get 256
as the output from wait()
. Using exit(-1)
gives 65280
.
有没有办法获取子进程发送的实际int值?
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);
使用 exit(-1)
(这是我真正想要的),我得到255作为 WEXITSTATUS(status)的输出代码>.它应该是未签名的吗?
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?
推荐答案
您是否尝试过"man waitpid"?
Have you tried "man waitpid"?
从waitpid()调用返回的值是退出值的编码.有一组宏将提供原始的退出值.或者,如果您不关心可移植性,则可以尝试将值右移8位.
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:
if(!(pid=fork()))
{
exit(1);
}
waitpid(pid,&status,0);
if (WIFEXITED(status)) {
printf("%d", WEXITSTATUS(status));
}
这篇关于为什么wait()将状态设置为255,而不是分叉进程的-1退出状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!