簡體   English   中英

system()的返回值不是執行程序的返回值

[英]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個字符。 你的strcpycommand之外破壞了一些記憶。 固定:

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的大小,或者直接使用文字字符串調用systemsystem("./test1")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM