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表示失败。
- Linux进程退出码
- Linux进程退出码
- Linux内核-进程退出
- Linux内核-进程退出
- LINUX监视进程退出
- Linux进程-进程的退出
- Linux下进程的退出
- linux内核进程退出分析
- Linux进程退出之方法论
- linux创建进程和等待进程退出
- Linux 进程--父进程查询子进程的退出状态
- Linux 进程--父进程查询子进程的退出状态
- Linux C 获取进程的退出值
- linux内核之进程退出do_exit
- linux-C子进程退出信号
- linux进程(四)之 退出
- TODO:Golang Linux进程退出说明
- linux 进程的创建 和退出回收
- Oracle创建自增字段方法-ORACLE SEQUENCE的简单介绍
- VB问题
- 翻译A Multiscale Retinex for Bridging the Gap Between Color Images and the Human Observation of Scenes
- Android 根据角度旋转图片
- oracle hints (摘录)
- Linux进程退出码
- windows编程——编译及向导安装
- 微信公众平台开发(三) 订阅事件(subscribe)处理
- HDU2006
- Android高级应用开发(基础篇) - stage10 - 学习笔记
- Request与Response
- FrameLayout---框架布局,帧布局//未完
- 【LeetCode】Permutations && Permutations II
- 宏 中使用 do {...;}while(0)的意义