2012-02-05 77 views
1

在我的程序中,我把這個代碼用於指示程序產生一個命令。這可以用來在我的程序中使用一個鍵啓動另一個程序,比如產生firefox。使用程序命令run_command「firefox」將有程序調用系統(「firefox &」)。警告:忽略'系統'的返回值c

case RUN_COMMAND: 
     if(arg) { 
      char commandline[ 256 ]; 
      snprintf(commandline, sizeof (commandline), "%s &", arg); 
      if(cmd->screen) { 
       char message[ 256 ]; 
       snprintf(message, sizeof (message), _("Running: %s"), arg); 
       screen_show_message(cmd->screen, message); 
      } 
      system(commandline); 
     } 
     break; 

當我編譯它給這個錯誤:

warning: ignoring return value of 'system', declared with attribute warn_unused_result [-Wunused-result] 
+2

這不是一個錯誤;它是一個*警告*(這就是爲什麼它被稱爲「警告」,而不是「錯誤」。)你的問題是什麼? – 2012-02-05 15:23:53

+0

可能重複[聲明屬性warn_unused_result \ [ - Wunused-result \]] (http://stackoverflow.com/questions/9148134/declared-with-attribute-warn-unused-result-wunused-result) – 2012-02-05 15:47:28

回答

8

這意味着你不應該認爲system將始終成功。你的代碼通過這種方式變得不可靠。應該有適當的錯誤處理。

0

這不是一個錯誤,它是一個警告。

它只是說你沒有檢查system()呼叫的回報。

Return Value

The value returned when the argument passed is not NULL, depends on the running environment specifications. In many systems, 0 is used to indicate that the command was successfully executed and other values to indicate some sort of error. When the argument passed is NULL, the function returns a nonzero value if the command processor is available, and zero otherwise.

你不應該認爲通話是成功的,並對待失敗。

7

警告意味着You did not check the return value of system(...)。 要避免此警告,只需檢查返回值!

int systemRet = system(commandLine); 
if(systemRet == -1){ 
    // The system method failed 
} 

這是,因爲system不保證成功。

+0

有時系統返回-1,但實際上成功。 – aloplop85 2016-08-05 07:48:42

5

庫編寫者將此函數聲明爲warn_unused_result,因爲他們認爲檢查調用是否成功很重要。你的一個編譯器標誌告訴編譯器檢查這個,所以它會警告你。避免警告的正確方法是檢查返回值並適當地處理錯誤(即使它只是打印錯誤信息)。在相關說明中,您應該檢查返回值snprintf以確保您的緩衝區足夠大。