[问题] system return value

楼主: EdisonX (卡卡兽)   2016-11-09 18:57:13
开发平台(Platform): (Ex: Win10, Linux, ...)
linux
编译器(Ex: GCC, clang, VC++...)+目标环境(跟开发平台不同的话需列出)
gcc / g++
额外使用到的函数库(Library Used): (Ex: OpenGL, ...)
no
问题(Question):
一些原因,我必须取得某个执行档的 return code,
即 echo $? 之值 但就是不想用 echo $? 去 pipe。
我查过了 cplusepluse.com 对 system 之说明,没
意会错的话应是说若呼叫该 command 失败传回 -1;
呼叫成功的话会是该 exe / library 之传回值,
也就是 main 的传回值。于是我写了二份 code 做测试
/// code 1 : test.cpp
int main(int argc, char **argv) {
return argc;
}
/// code 2 : test2.cpp
#include <cstdio>
#include <cstdlib>
int main(int argc, char ** argv) {
printf("%d\n", system(".....ERRORCMD...."));
printf("%d\n", system("./test"));
printf("%d\n", system("./test 1"));
printf("%d\n", system("./test 1 2"));
return 0;
}
/// result
32512
256
512
768
这几个数值看起来是用 bitwise 代表 status,
但和我预期传回的
-1
1
2
3
有很大的落差 ,请问我是不是误会什么了?问题主要二个
(1) 不用 pipe 如何取得另一个执行档之 return value ?
(2) 请问 system 之 return value 意义为何 ??-
先谢谢各位的不吝解惑。
作者: Schottky (顺风相送)   2016-11-09 19:11:00
不要用 system(),使用 vfork() + exec()然后使用 wait() 或 waitpid() 就可以取得return statussystem 会去呼叫 shell 再叫 shell 执行你的指令
作者: stimim (qqaa)   2016-11-09 19:14:00
The value returned is -1 on error (e.g., fork(2)and the return status of the command otherwise.This latter return status is in the format specifiedin wait(2). Thus the exit code of the command will beWEXITSTATUS(status).
作者: pttworld (批踢踢世界)   2016-11-09 19:19:00
argc不就是argv的数量,回传?goo.gl/GT3OIo
作者: Schottky (顺风相送)   2016-11-09 19:25:00
啊啊我看懂你的问题了,你要的值要用 WEXITSTATUS() 去取
楼主: EdisonX (卡卡兽)   2016-11-10 00:19:00
疑!所以我没意会错推文意思的话,就变成WEXITSTATUS( system(pszCmd) ) ; 了吗 ??
作者: Schottky (顺风相送)   2016-11-10 01:00:00
话是不错,但你这个写程式的习惯很不好把 status 先存到变量里比较清楚,而且你有可能需要不只一个判断或取值
楼主: EdisonX (卡卡兽)   2016-11-10 01:50:00
了解!谢谢各位的解答,感谢!!

Links booklink

Contact Us: admin [ a t ] ucptt.com