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

标签 c wait

我有这个代码:

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/

相关文章:

c - 如何确定使用哪个 D-Bus 绑定(bind)

c - 如何在 ST monad 中执行 FFI 调用

Java如何延迟程序执行

ios - 如何在没有超时错误的情况下在 XCTest 中等待 T 秒?

c++ - 来自事件处理程序的 STM32 函数指针

c - make 找不到 sys/signal.h

c - 有没有办法制作一个函数来计算 C 中 x 指数的 10? "ten_to_the(x exponent)"

c - 如何 fork 并创建执行相同任务的特定数量的 child ?

java - ProcessBuilder和Process.waitFor(),它等了多久?

powershell - 如何告诉 PowerShell 等待每个命令结束后再开始下一个命令?