popen函数
popen通过创建管道的方式来启动一个进程,并调用 shell. 因为管道是被定义成单向的, 所以 type 参数只能定义成只读或者只写, 不能是两者同时, 结果流也相应的是只读或者只写
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
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比system在应用中的好处:可以获取运行的输出结果。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
char ret[1024] = {0};
FILE *fp;
fp = popen("ps", "r"); //以可读方式调用PS命令
int nread = fread(ret, 1, 1024, fp);//写入到ret,返回写入的字符大小
pclose(fp);
printf("read % byte, ret = %s\n", nread, ret);
return 0;
}