背景:工作中遇到一个system函数执行udhcp失败返回256的问题,一开始以为这个函数有问题,
经过一番分析,查到system返回256,相当于shell命令返回值为1
std::system - cppreference.com
https://en.cppreference.com/w/cpp/utility/program/system
返回值可以使用WEXITSTATUS 解析的
Return value
Implementation-defined value. If
commandis a null pointer, returns a nonzero value if and only if the command processor exists.Notes
On POSIX systems, the return value can be decomposed using WEXITSTATUS and WSTOPSIG
The related POSIX function popen makes the output generated by
commandavailable to the caller.An explicit flush of std::cout is also necessary before a call to std::system, if the spawned process performs any screen I/O.
wait
https://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html
WEXITSTATUS(stat_val)
If the value of WIFEXITED(stat_val) is non-zero, this macro evaluates to the low-order 8 bits of the status argument that the child process passed to _exit() or exit(), or the value the child process returned from main().
这儿意思是拿低8位,猜测应该有可能有大小端?正好256,拿高八位 为1,暂时这么理解吧
- ls: 无法访问/noexist: 没有那个文件或目录
- libin@libin:~/program/C/Linux/system$ echo $?
- 2
- libin@libin:~/program/C/Linux/system$
我们看到了,虽然/noexist文件并不存在,ls这条命令执行出了错,但是仍然属于shell顺利执行完毕。 ls /noexist的错误吗是2,所以,system函数的返回值为 2*256 = 512.
当使用std::system函数执行命令时,返回值256对应于shell命令的退出状态码1。在POSIX系统中,可以通过WEXITSTATUS宏来解析返回值的低8位。博客探讨了这一问题,包括如何判断脚本执行是否成功,以及错误代码与shell执行状态的关系。内容还涉及了ls命令返回错误码2及其与system返回值的计算方式。
https://blog.youkuaiyun.com/mct_blog/article/details/54408255
670

被折叠的 条评论
为什么被折叠?



