[問題] 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