popen && pclose函數
1. 函數操作:
創建一個管道,調用fork產生一個子進程,關閉管道的不使用端,執行一個shell以運行命令,然後等待命令終止;
2. 函數原型:
#include <stdio.h> FILE *popen(const char *cmdstring, const char *type); ret = 成功返回文件指針,失敗返回NULL int pclose(FILE *fp); ret = cmdstring的終止狀態,失敗返回-1
函數popen先執行fork,然後調動exec執行cmdstring,並且返回一個標準IO文件指針,如果type='r',則文件指針連接到cmdstring的標準輸出,如果type='w',則文件指針連接
到cmdstring的標準輸入;
函數pclose關閉IO流,等待命令執行結束,返回shell終止狀態,如果shell不能被執行,則返回終止狀態與shell執行exit(127)一樣;
3. 與system函數比較:
popen函數可以通過管道和shell進程進行通信,而system只是執行命令返回是否成功,如果程序中不需要與shell有數據交互,使用system比較適合;
4. 測試代碼:執行ls . 獲取當前目錄中文件列表
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 #define BUF_LEN 128 5 6 int main(int argc, char * argv[]) 7 { 8 FILE *fp = NULL; 9 10 char buf[BUF_LEN] = { 0 }; 11 12 if ((fp = popen("ls .", "r")) == NULL){ 13 perror("popen error\n"); 14 return -1; 15 } 16 17 while (fgets(buf, BUF_LEN, fp) != NULL){ 18 printf("%s", buf); 19 } 20 21 pclose(fp); 22 23 return 0; 24 }
結果:
test_popen test_popen.c