1 应用场景
最近在实际程序开发中,需要通过程序执行 shell 命令,并获取命令输出内容。但是系统自带的 system 只能返回命令执行成功与否,不能捕获命令输出。
2 扩展性
由于应用场景本就广泛,因此扩展性较好。
此函数可以执行任意命令,并捕获命令输出结果。
实际使用过程中可以把此函数作为最底层接口,然后层层封装,实现自己想要的功能。
3 测试环境
3.1 Ubuntu
找到此方法时,我首先在 Ubuntu 中进行了测试,环境如下:
系统版本:Ubuntu 14.04.1 LTS
系统版本详细信息如下
1zhaoc@ubuntu14:~$lsb_release-a2NoLSBmodulesareavailable.3DistributorID:Ubuntu4Description:Ubuntu14.04.1LTS5Release:14.046Codename:trusty
系统内核版本如下
1zhaoc@ubuntu14:~$uname-a2Linuxubuntu143.13.0-32-generic#57-UbuntuSMPTueJul1503:51:08UTCx86_64x86_64x86_64GNU/Linux
gcc 版本如下
1gccversion4.8.2(Ubuntu4.8.2-19ubuntu1)
3.2 工程代码
随后又放到工程代码中测试,环境如下:
系统内核版本如下
1[root]#uname-a2Linuxitl4.4.207 #24PREEMPTFriJan2918:09:37CSTarmv5tejlGNU/Linux
gcc 版本如下
1gccversion4.8.30320(prerelease)(SourceryCodeBenchLite.05-29)
使用 C 标准:C 11
4 函数原型
根据参考资料,优化后的函数原型如下
1#include2#include34#defineCMD_RESULT_BUF_SIZE102456/*7* cmd:待执行命令8* result:命令输出结果9*函数返回:0成功;-1 失败;10*/11intExecuteCMD(constchar*cmd,char*result)12{13intiRet=-1;14charbuf_ps[CMD_RESULT_BUF_SIZE];15charps[CMD_RESULT_BUF_SIZE]={0};16FILE*ptr;1718strcpy(ps,cmd);1920if((ptr=popen(ps,"r"))!=NULL)21{22while(fgets(buf_ps,sizeof(buf_ps),ptr)!=NULL)23{24strcat(result,buf_ps);25if(strlen(result)>CMD_RESULT_BUF_SIZE)26{27break;28}29}30pclose(ptr);31ptr=NULL;32iRet=0;//处理成功33}34else35{36printf("popen%serror\n",ps);37iRet=-1;//处理失败38}3940returniRet;41}
查看源码中的 popen() 、pclose() 函数原型定义如下:
1#if(defined__USE_POSIX2||defined__USE_SVID||defined__USE_BSD||\2defined__USE_MISC)3/*Createanewstreamconnectedtoapiperunningthegivencommand.45Thisfunctionisapossiblecancellationpointandthereforenot6markedwith__THROW.*/7externFILE*popen(constchar*__command,constchar*__modes)__wur;89/*Closeastreamopenedbypopenandreturnthestatusofitschild.1011Thisfunctionisapossiblecancellationpointandthereforenot12markedwith__THROW.*/13externintpclose(FILE*__stream);14#endif
查看源码中的 fgets() 函数原型如下:
1/*Getanewline-terminatedstringoffinitelengthfromSTREAM.23Thisfunctionisapossiblecancellationpointandthereforenot4markedwith__THROW.*/5externchar*fgets(char*__restrict__s,int__n,FILE*__restrict__stream)6__wur;
声明:
本文于网络整理,版权归原作者所有,如来源信息有误或侵犯权益,请联系我们删除或授权事宜。