gpt4 book ai didi

c - 我用了wait(&status),status的值为256,为什么?

转载 作者:太空狗 更新时间:2023-10-29 17:00:38 25 4
gpt4 key购买 nike

我有这个代码:

int status;
t = wait(&status);

当子进程工作时,status的值为0,嗯。

但是为什么不行就返回256呢?为什么在出现错误时更改子进程中退出的参数值不会改变任何内容(例如 exit(2) 而不是 exit(1))?

编辑:我在 linux 上,我用 GCC 编译。

最佳答案

给定这样的代码...

int main(int argc, char **argv) {
pid_t pid;
int res;

pid = fork();
if (pid == 0) {
printf("child\n");
exit(1);
}

pid = wait(&res);
printf("raw res=%d\n", res);

return 0;
}

...res 的值将为 256。这是因为 wait 的返回值编码了进程的退出状态以及进程退出的原因。通常,您不应尝试直接解释 wait 的非零返回值;您应该使用 WIF... 宏。例如查看一个进程是否正常退出:

 WIFEXITED(status)
True if the process terminated normally by a call to _exit(2) or
exit(3).

然后获取退出状态:

 WEXITSTATUS(status)
If WIFEXITED(status) is true, evaluates to the low-order 8 bits
of the argument passed to _exit(2) or exit(3) by the child.

例如:

int main(int argc, char **argv) {
pid_t pid;
int res;

pid = fork();
if (pid == 0) {
printf("child\n");
exit(1);
}

pid = wait(&res);
printf("raw res=%d\n", res);

if (WIFEXITED(res))
printf("exit status = %d\n", WEXITSTATUS(res));
return 0;
}

您可以在 wait(2) 手册页中阅读更多详细信息。

关于c - 我用了wait(&status),status的值为256,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24130990/

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