极简风格的网站,wordpress建站事项,做网站送白酒,网站的推广和优化方案1 应用场景最近在实际程序开发中#xff0c;需要通过程序执行 shell 命令#xff0c;并获取命令输出内容。但是系统自带的 system 只能返回命令执行成功与否#xff0c;不能捕获命令输出。2 扩展性由于应用场景本就广泛#xff0c;因此扩展性较好。此函数可以执行任意命令需要通过程序执行 shell 命令并获取命令输出内容。但是系统自带的 system 只能返回命令执行成功与否不能捕获命令输出。2 扩展性由于应用场景本就广泛因此扩展性较好。此函数可以执行任意命令并捕获命令输出结果。实际使用过程中可以把此函数作为最底层接口然后层层封装实现自己想要的功能。3 测试环境3.1 Ubuntu找到此方法时我首先在 Ubuntu 中进行了测试环境如下系统版本Ubuntu 14.04.1 LTS系统版本详细信息如下1zhaocubuntu14:~$ lsb_release -a
2No LSB modules are available.
3Distributor ID: Ubuntu
4Description: Ubuntu 14.04.1 LTS
5Release: 14.04
6Codename: trusty系统内核版本如下1zhaocubuntu14:~$ uname -a
2Linux ubuntu14 3.13.0-32-generic #57-Ubuntu SMP Tue Jul 15 03:51:08 UTC 2014 x86_64 x86_64 x86_64 GNU/Linuxgcc 版本如下1gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) 3.2 工程代码随后又放到工程代码中测试环境如下系统内核版本如下1[root]#uname -a
2Linux itl 4.4.207 #24 PREEMPT Fri Jan 29 18:09:37 CST 2021 armv5tejl GNU/Linuxgcc 版本如下1gcc version 4.8.3 20140320 (prerelease) (Sourcery CodeBench Lite 2014.05-29)使用 C 标准C 114 函数原型根据参考资料优化后的函数原型如下 1#include 2#include 34#define CMD_RESULT_BUF_SIZE 102456/*7 * cmd待执行命令8 * result命令输出结果9 * 函数返回0 成功-1 失败
10 */
11int ExecuteCMD(const char *cmd, char *result)
12{
13 int iRet -1;
14 char buf_ps[CMD_RESULT_BUF_SIZE];
15 char ps[CMD_RESULT_BUF_SIZE] {0};
16 FILE *ptr;
17
18 strcpy(ps, cmd);
19
20 if((ptr popen(ps, r)) ! NULL)
21 {
22 while(fgets(buf_ps, sizeof(buf_ps), ptr) ! NULL)
23 {
24 strcat(result, buf_ps);
25 if(strlen(result) CMD_RESULT_BUF_SIZE)
26 {
27 break;
28 }
29 }
30 pclose(ptr);
31 ptr NULL;
32 iRet 0; // 处理成功
33 }
34 else
35 {
36 printf(popen %s error\n, ps);
37 iRet -1; // 处理失败
38 }
39
40 return iRet;
41}查看源码中的 popen() 、pclose() 函数原型定义如下 1#if (defined __USE_POSIX2 || defined __USE_SVID || defined __USE_BSD || \2 defined __USE_MISC)3/* Create a new stream connected to a pipe running the given command.45 This function is a possible cancellation point and therefore not6 marked with __THROW. */7extern FILE *popen (const char *__command, const char *__modes) __wur;89/* Close a stream opened by popen and return the status of its child.
10
11 This function is a possible cancellation point and therefore not
12 marked with __THROW. */
13extern int pclose (FILE *__stream);
14#endif查看源码中的 fgets() 函数原型如下1/* Get a newline-terminated string of finite length from STREAM.
2
3 This function is a possible cancellation point and therefore not
4 marked with __THROW. */
5extern char *fgets (char *__restrict __s, int __n, FILE *__restrict __stream)
6 __wur;声明本文于网络整理版权归原作者所有如来源信息有误或侵犯权益请联系我们删除或授权事宜。