歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux綜合 >> 學習Linux >> system系統調用返回值判斷命令是否執行成功,system系統調用

system系統調用返回值判斷命令是否執行成功,system系統調用

日期:2017/3/6 9:33:14   编辑:學習Linux

system系統調用返回值判斷命令是否執行成功,system系統調用


system系統調用返回值判斷命令是否執行成功,system系統調用


system函數對返回值的處理,涉及3個階段:

階段1:創建子進程等准備工作。如果失敗,返回-1。 階段2:調用/bin/sh拉起shell腳本,如果拉起失敗或者shell未正常執行結束(參見備注1),原因值被寫入到status的低8~15比特位中。system的man中只說明了會寫了127這個值,但實測發現還會寫126等值。 階段3:如果shell腳本正常執行結束,將shell返回值填到status的低8~15比特位中。 備注1: 只要能夠調用到/bin/sh,並且執行shell過程中沒有被其他信號異常中斷,都算正常結束。 比如:不管shell腳本中返回什麼原因值,是0還是非0,都算正常執行結束。即使shell腳本不存在或沒有執行權限,也都算正常執行結束。 如果shell腳本執行過程中被強制kill掉等情況則算異常結束。 如何判斷階段2中,shell腳本是否正常執行結束呢?系統提供了宏:WIFEXITED(status)。如果WIFEXITED(status)為真,則說明正常結束。 如何取得階段3中的shell返回值?你可以直接通過右移8bit來實現,但安全的做法是使用系統提供的宏:WEXITSTATUS(status)。 由於我們一般在shell腳本中會通過返回值判斷本腳本是否正常執行,如果成功返回0,失敗返回正數。 所以綜上,判斷一個system函數調用shell腳本是否正常結束的方法應該是如下3個條件同時成立: (1)-1 != status (2)WIFEXITED(status)為真 (3)0 == WEXITSTATUS(status) 因此,我們可以由下面代碼判斷命令是否正常執行並返回: 1 bool mySystem(const char *command) 2 { 3 int status; 4 status = system(command); 5 6 if (-1 == status) 7 { 8 printf("mySystem: system error!"); 9 return false; 10 } 11 else 12 { 13 if (WIFEXITED(status)) 14 { 15 if (0 == WEXITSTATUS(status)) 16 { 17 return true; 18 } 19 printf("mySystem: run shell script fail, script exit code: %d\n", WEXITSTATUS(status)); 20 return false; 21 } 22 printf("mySystem: exit status = [%d]\n", WEXITSTATUS(status)); 23 return false; 24 } 25 } 26 View Code

http://xxxxxx/Linuxjc/1140543.html TechArticle

Copyright © Linux教程網 All Rights Reserved