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