作者EdisonX (卡卡兽)
看板C_and_CPP
标题[问题] system return value
时间Wed Nov 9 18:57:13 2016
开发平台(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 意义为何 ??-
先谢谢各位的不吝解惑。
--
就算把新鲜的肝拿回去,还是一样写码到秃头,加班到天亮,
永远当老板的傀儡 你是不是想这麽做?
是的话你就拿回去~ 拿啊!!
九世宅男 : 下辈子不要再让我干工程师了 ~
< Kuso 星爷语录 >
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 60.251.92.140
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1478689043.A.86D.html
※ 编辑: EdisonX (60.251.92.140), 11/09/2016 18:59:15
1F:→ Schottky: 不要用 system(),使用 vfork() + exec() 11/09 19:11
2F:→ Schottky: 然後使用 wait() 或 waitpid() 就可以取得return status 11/09 19:12
3F:→ Schottky: system 会去呼叫 shell 再叫 shell 执行你的指令 11/09 19:13
4F:推 stimim: The value returned is -1 on error (e.g., fork(2) 11/09 19:14
5F:→ stimim: and the return status of the command otherwise. 11/09 19:14
6F:→ stimim: This latter return status is in the format specified 11/09 19:15
7F:→ stimim: in wait(2). Thus the exit code of the command will be 11/09 19:15
8F:→ stimim: WEXITSTATUS(status). 11/09 19:15
9F:→ pttworld: argc不就是argv的数量,回传? 11/09 19:19
10F:→ pttworld: goo.gl/GT3OIo 11/09 19:25
11F:→ Schottky: 啊啊我看懂你的问题了,你要的值要用 WEXITSTATUS() 去取 11/09 19:25
12F:→ EdisonX: 疑!所以我没意会错推文意思的话,就变成 11/10 00:19
13F:→ EdisonX: WEXITSTATUS( system(pszCmd) ) ; 了吗 ?? 11/10 00:19
14F:→ Schottky: 话是不错,但你这个写程式的习惯很不好 11/10 01:00
15F:→ Schottky: 把 status 先存到变数里比较清楚,而且你有可能需要 11/10 01:01
16F:→ Schottky: 不只一个判断或取值 11/10 01:02
17F:→ EdisonX: 了解!谢谢各位的解答,感谢!! 11/10 01:50