[英]Return value of system() is not return value of executed program
我想執行一個可執行文件,其main()使用system()
返回2。 這就是我做的
#include <stdio.h>
#include <string.h>
int main(int argc, char *agrv[])
{
char command[7];
strcpy(command, "./test1");
printf("The return value: %d\n", system(command));
return 0;
}
和test1
是
#include <stdio.h>
int main(void)
{
printf("test1 has been executed and its return value is 2\n");
return 2;
}
這就是我得到的
test1 has been executed and its return value is 2
The return value: 512
我的問題是為什么我得到512
。
引用man 3 system
:
錯誤時返回的值為
-1
(例如fork
(2)失敗),否則返回命令的返回狀態。 后一種返回狀態采用wait
(2)中指定的格式。 因此,命令的退出代碼將是WEXITSTATUS(status)
。
man 2 wait
顯示其他信息被打包到system
(3)返回的status
。
512
表示程序退出,退出狀態為2。 2
意味着程序被信號2(SIGINT)殺死。 請注意,由於尾隨NUL,字符串./test1
需要8個字符。 你的strcpy
在command
之外破壞了一些記憶。 固定:
char command[8];
strcpy(command, "./test1");
當然,沒有理由首先制作副本。
const char* command = "./test1";
system(command)
甚至
system("./test1")
系統的返回值實際上是POSIX下waitpid()的返回值。
status
實際上嵌入了很多信息:
從系統(3)手冊頁:
以下宏可用於測試進程退出的方式。 前三個宏中的一個將評估為非零(真)值:
WIFEXITED(status)
如果通過調用_exit(2)或exit(3)正常終止進程,則為
True
。
WIFSIGNALED(status)
如果由於收到信號而終止進程,則為
True
。
WIFSTOPPED(status)
如果進程尚未終止,但已停止並可以重新啟動,則為
True
。
僅當等待調用指定了WUNTRACED
選項或正在跟蹤子進程時,此宏才可以為true(請參閱ptrace(2))。根據這些宏的值,以下宏將生成有關子進程的剩余狀態信息:
WEXITSTATUS(status)
如果
WIFEXITED(status)
為true
,則計算子項傳遞給_exit(2)或exit(3)的參數的低位8位。
WTERMSIG(status)
如果
WIFSIGNALED(status)
為true
,則計算導致進程終止的信號編號。
WCOREDUMP(status)
如果
WIFSIGNALED(status)
為true
,則如果進程終止伴隨着在收到信號時創建包含進程映像的核心文件,則計算結果為true。
WSTOPSIG(status)
如果
WIFSTOPPED(status)
為true
,則計算導致進程停止的信號編號。
#include <stdio.h>
#include <string.h>
#include <limits.h>
int main(int argc, char *argv[])
{
int status;
char command[PATH_MAX]; /* PATH_MAX is defined in sys/syslimits.h, included by limits.h */
strcpy(command, "./test1");
status = system(command);
if ( WIFEXITED(status) ) {
printf("The return value: %d\n", WEXITSTATUS(status));
}
else if (WIFSIGNALED(status)) {
printf("The program exited because of signal (signal no:%d)\n", WTERMSIG(status));
}
return 0;
}
事實上,這是未定義的行為。 command
只保存7個字符,但字符串"./test1"
有8個,包括空終止符。 您需要增加command
的大小,或者直接使用文字字符串調用system
: system("./test1")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.