Linux进程退出码

来源:互联网 发布:a站ceo莫然离职 知乎 编辑:程序博客网 时间:2024/05/21 09:45

首先,我们写一个测试程序,很简单,几行代码:

#include <stdio.h>int main(void){    return -1;}

编译好,然后运行,然后在shell里面查看进程退出码,键入:echo $?,我们发现拿到的进程退出码是255。

我们返回的明明是-1,为什么拿到的却是255呢?还得从进程的状态码开始讲起,我们知道,当一个进程退出的时候,父进程一般都会进行收尾工作,就是调用wait或者waitpid获取进程的状态码,就是status code,我们从这两个系统调用的函数原型就可以看出:

pid_t wait(int *status);
pid_t waitpid(pid_t pid, int *status, int options);

status指针可以传出拿到的状态码信息,但是状态码不等于退出码,就是说status code ≠ exit code,我们先来看状态码的构成:

The exit status returned by 'wait()' is a 16-bit value. Of those 16 bits, the high-order 8 bits come from the low-order 8 bits of the value returned by 'exit()' - or the value returned from main(). If the program dies naturally, the low-order 8 bits of the 16 are all zero. If the program dies because of signal, the low-order 8 bits encode the signal number and a bit indicating whether a core dump happened. With a signal, the exit status is treated as zero - programs like the shell tend to interpret the low-order bits non-zero as a failure.

+-----------------+|  exit  | signal |+-----------------+

Most machines actually store the 16-bit value in a 32-bit integer, and that is handled with unsigned arithmetic.

上面这段英文来自stackoverflow的一段话,就是说进程退出时候的状态码是16位,高八位存储退出码,低八位存储导致进程退出的信号标志位,那么现在既然知道了状态码的构成,取出程序的退出码就不难了,不过这个不用我们自己写代码,Linux已经提供了相应的宏:WEXITSTATUS,这个宏用来从状态码中取出退出码。

回到我们的话题,为什么返回的是255的问题,-1对应到八位二进制那就是 1111 1111,全是1,把它作为无符号数,那就是255。为什么不能把它当成有符号数呢?因为退出码范围0-255是POSIX 1003.1标准规范化了的,不能超出这个范围。
总结:最好是不要用exit(-1)或者在main函数里面返回-1,这个是很不好的习惯,可以使用宏:EXIT_SUCCESS表示成功,EXIT_FAILURE表示失败。

0 0