popen && pclose函數

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章