直接贴代码:
#include <stdio.h>
#include <string.h>
#include <errno.h> int main(int argc,char*argv[])
{
FILE *fstream=NULL;
char buff[];
memset(buff,,sizeof(buff));
if(NULL==(fstream=popen("uname -a","r")))
{
fprintf(stderr,"execute command failed: %s",strerror(errno));
return -;
}
if(NULL!=fgets(buff, sizeof(buff), fstream))
{
printf("=>%s",buff);
}
else
{
pclose(fstream);
return -;
}
pclose(fstream);
return ;
}
结果输出是这样子的:
merlin@tfAnalysis:~/t/popen$ ./a.out
=>Linux tfAnalysis 3.13.--generic #-Ubuntu SMP Fri Aug :: UTC i686 i686 i686 GNU/Linux
merlin@tfAnalysis:~/t/popen$
还有另外的方法是将输出重定位到某个tmp文件中,然后再打开该文件获得数据。