LinuxC
進程I/O函式,與pclose函式一起使用。表頭檔案#include 函式定義FILE * popen ( const char * command , const char * type );int pclose ( FILE * stream );函式說明popen() 函式通過創建一個管道,調用 fork 產生一個子進程,執行一個 shell 以運行命令來開啟一個進程。這個進程必須由 pclose() 函式關閉,而不是 fclose() 函式。pclose() 函式關閉標準 I/O 流,等待命令執行結束,然後返回 shell 的終止狀態。如果 shell 不能被執行,則 pclose() 返回的終止狀態與 shell 已執行 exit 一樣。 type 參數只能是讀或者寫中的一種,得到的返回值(標準 I/O 流)也具有和 type 相應的唯讀或只寫類型。如果 type 是 "r" 則檔案指針連線到 command 的標準輸出;如果 type 是 "w" 則檔案指針連線到 command 的標準輸入。 command 參數是一個指向以 NULL 結束的 shell 命令字元串的指針。這行命令將被傳到 bin/sh 並使用-c 標誌,shell 將執行這個命令。 popen 的返回值是個標準 I/O 流,必須由 pclose 來終止。前面提到這個流是單向的。所以向這個流寫內容相當於寫入該命令的標準輸入;命令的標準輸出和調用 popen 的進程相同。與之相反的,從流中讀數據相當於讀取命令的標準輸出;命令的標準輸入和調用 popen 的進程相同。返回值如果調用 fork() 或 pipe() 失敗,或者不能分配記憶體將返回NULL,否則返回標準 I/O 流。返回錯誤popen 沒有為記憶體分配失敗設定 errno 值。如果調用 fork() 或 pipe() 時出現錯誤,errno 被設為相應的錯誤類型。如果 type 參數不合法,errno將返回EINVAL。使用舉例if((fp=popen("/usr/bin/uptime","r"))==NULL);{sprintf(buf,"error: %s\n", strerror(errno));....//異常處理}else{....pclose(fp);}
真實示例
1234567891011121314151617181920212223242526272829#define _LINE_LENGTH 300intget_path_total(constchar*path, longlong* total) {interr=-1;FILE*file;charline[_LINE_LENGTH];char*p;chartmp;char*token;sprintf(tmp, "df %s", path);file = popen(tmp, "r");if(file != NULL) {if(fgets(line, _LINE_LENGTH, file) != NULL) {if(fgets(line, _LINE_LENGTH, file) != NULL) {token = strtok(line, " ");if(token != NULL) {// printf("token=%s\n", token);}token = strtok(NULL, " ");if(token != NULL) {// printf("token=%s\n", token);*total=atoll(token)/1024;//k/1024err=0;}}}pclose(file);}returnerr;}
