Linux 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

 

posted @ 2016-03-19 22:23  AlexAlex  阅读(1662)  评论(0编辑  收藏  举报