1. 函数操作:
创建一个管道,调用fork产生一个子进程,关闭管道的不使用端,执行一个shell以运行命令,然后等待命令终止;
2. 函数原型:
#include <stdio.h> FILE *popen(const char *cmdstring, const char *type); ret = 成功返回文件指针,失败返回NULL int pclose(FILE *fp); ret = cmdstring的终止状态,失败返回-
函数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 . 获取当前目录中文件列表
#include <stdio.h>
#include <stdlib.h> #define BUF_LEN 128 int main(int argc, char * argv[])
{
FILE *fp = NULL; char buf[BUF_LEN] = { }; if ((fp = popen("ls .", "r")) == NULL){
perror("popen error\n");
return -;
} while (fgets(buf, BUF_LEN, fp) != NULL){
printf("%s", buf);
} pclose(fp); return ;
}
结果:
test_popen
test_popen.c