原文:https://blog.csdn.net/libinbin_1014/article/details/51490568
相比于system函数,popen()函数可以获取运行的输出结果。
popen()函数代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//FILE *popen(const char *command, const char *type);
//int pclose(FILE *stream);
int main(void)
{
FILE *fp;
int n_read;
char ret[1024] = {0};
fp = popen("ps", "r");
//size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
n_read = fread(ret, 1, 1024, fp);
printf("read %d bytes,context: %s\n", n_read, ret);
fclose(fp);
return 0;
}
运行结果: