http://linux.chinaitlab.com/c/806015.html
函數原型:
#include “stdio.h”
FILE *popen( const char* command, const char* mode )
參數說明:
command: 是一個指向以 NULL 結束的 shell 命令字串的指標。這行命令將被傳到 bin/sh 並使用 -c 標誌,shell 將執行這個命令。
mode: 只能是讀或者寫中的一種,得到的傳回值(標準 I/O 流)也具有和 type 相應的唯讀或唯寫類型。如果 type 是 “r” 則檔案指標串連到 command 的標準輸出;如果 type 是 “w” 則檔案指標串連到command 的標準輸入。
傳回值:
如果調用成功,則返回一個讀或者開啟檔案的指標,如果失敗,返回NULL,具體錯誤要根據errno判斷
int pclose (FILE* stream)
參數說明:
stream:popen返回的檔案指標
傳回值:
如果調用失敗,返回 -1
作用:
popen() 函數用於建立一個管道:其內部實現為調用 fork 產生一個子進程,執行一個 shell 以運行命令來開啟一個進程這個進程必須由 pclose() 函數關閉。
例子:
管道讀:先建立一個檔案test,然後再test檔案內寫入“Readpipe successfully !”
#include “stdio.h”
#include “stdlib.h”
int main()
{
FILE *fp;
char buf[200] = {0};
if((fp = popen(“cat test”, “r”)) == NULL) {
perror(“Fail to popen\n”);
exit(1);
}
while(fgets(buf, 200, fp) != NULL) {
printf(“%s”, buf);
}
pclose(fp);
return 0;
}
列印輸出: Read pipe successfully !
管道讀:
#include “stdio.h”
#include “stdlib.h”
int main()
{
FILE *fp;
char buf[200] = {0};
if((fp = popen(“cat > test1″, “w”)) == NULL) {
perror(“Fail to popen\n”);
exit(1);
}
fwrite(“Read pipe successfully !”, 1, sizeof(“Read pipe successfully!”), fp);
pclose(fp);
return 0;
}
執行完畢後,目前的目錄下多了一個test1檔案,開啟,裡面內容為Read pipe successfully !