#include <stdio.h>
FILE *popen(const char *command, const char *mode);
int pclose(FILE *stream);
/*
command: 是一个指向以 NULL 结束的 shell 命令字符串的指针。这行命令将被传到 bin/sh 并使用 -c 标志,shell 将执行这个命令。
mode:只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。如果 type 是 “r” 则文件指针连接到 command 的标准输出;如果 type 是 “w” 则文件指针连接到 command 的标准输入。
stream:popen返回的文件指针
如果调用失败,返回 -1
返回值:
调用成功,则返回一个读或者打开文件的指针,
失败,返回NULL,具体错误要根据errno判断
*/
比system在应用中的好处:可以获取运行的输出结果。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
//size_t fread(void *ptr,size_t size,size_t nmemb,FILE *stream);
int main()
{
char ret[1024];
FILE *fp;
fp = popen("ps","r");
//system("ps");
int nread = fread(ret,1,1024,fp);
printf("read ret %d byte , ret = %s\n",nread,ret);
/*用system,ret = 空,无法保存*/
return 0;
}
linux下popen的使用
https://blog.youkuaiyun.com/libinbin_1014/article/details/51490568