我用了wait(&status),status的值为256,为什么? [英] I used wait(&status) and the value of status is 256, why?

查看:40
本文介绍了我用了wait(&status),status的值为256,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有这一行:

t = wait(&status); 

子进程工作时,status的值为0,好吧.

When the child process works, the value of status is 0, well.

但是为什么它不起作用时返回256?为什么在出现错误时更改给子进程中退出的参数值不会改变任何东西(例如,exit(2) 而不是 exit(1))?

But why does it return 256 when it doesn't work? And why changing the value of the argument given to exit in the child process when there is an error doesn't change anything (exit(2) instead of exit(1) for example)?

谢谢

我在 linux 上,我用 GCC 编译.

Edit : I'm on linux, and I compiled with GCC.

我这样定义状态

int status;
t = wait(&status); 

推荐答案

给定这样的代码...

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... 宏.比如查看一个进程是否正常退出:

...the value of res will be 256. This is because the return value from wait encodes both the exit status of the process as well as the reason the process exited. In general, you should not attempt to interpret non-zero return values from wait directly; you should use of the WIF... macros. For example, to see if a process exited normally:

 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) 手册页中阅读更多详细信息.

You can read more details in the wait(2) man page.

这篇关于我用了wait(&status),status的值为256,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆