最近在專案中用到了c語言執行shell命令的問題,調查了一下,一般有system函式、exec族函式,但是還不太清楚怎麼獲取shell命令執行的返回資訊。
例如執行乙個ifconfig命令,肯定需要獲取ifconfig命令的返回值的。
接著調查的話,發現有乙個popen函式,也可以執行shell命令,並且可以獲取shell命令執行的返回資訊。
man popen可以看到:
#include file *popen(const char *command, const char *type);
int pclose(file *stream);
示例:
#include#include#includeint main(int argc,char*argv)
while(null!=fgets(buff, sizeof(buff), fstream))
pclose(fstream);
return 0;
}
用這個示例測試乙個mount命令,一不小心把ip位址弄錯了,結果到了pclose時,好長時間都沒有返回。
檢視了一些資料,發現popen是建立乙個子程序執行shell命令,用pclose銷毀子程序並**資源,所以pclose會一直等待子程序的退出。
所以在用popen執行某個shell命令時,最好可以讓該shell命令可以在一定時間內返回。
補充一點:
在用popen執行mount命令時,用上述**無法捕獲mount的錯誤資訊。
例如故意將mount的引數寫錯,在用fgets時,無法獲取到mount的錯誤資訊;雖然在終端上可以看到mount的錯誤資訊,但是fgets無法獲取。
想到是不是mount的錯誤資訊沒有輸出到stdout,為了證實猜測,就在mount命令的最後加上了2>&1,就是錯誤資訊重定向到stdout,結果fgets就可以獲取到mount的錯誤資訊了。
linux c語言執行shell命令
int system const char command 輸入command指的是要執行的shell命令。file popen const char command,const char type int pclose file stream popen函式是首先fork乙個子程序,然後exec,...
Linux C中呼叫shell命令
很多時候我們需要在我們所編寫的c程式當中,呼叫一行命令,在命令列執行的命令,比如ifconfig,ls,或者是其他需要的命令如mpirun machinefile host np mpi並行程式 等等,這就要求我們能夠在linux下呼叫shell命令。linux的c就為我們提供了乙個可以呼叫shel...
Android執行shell命令
android執行shell命令 一 方法 執行乙個shell命令,並返回字串值 param cmd 命令名稱 引數組成的陣列 例如 param workdirectory 命令執行路徑 例如 system bin return 執行結果組成的字串 throws ioexception public...