近来C++技术交流群发觉了好多水平很高的同学,欢迎你们来加喵哥陌陌,进群一起讨论计算机知识!
程序喵大人陌陌
祝你们身体健康,工作顺利,蛇年大吉!
1参考资料
1、【c/c++】如何调用【linux】shell命令行命令并获取命令行的输出内容()
2使用说明2.1应用场景
近来在实际程序开发中,须要通过程序执行shell命令linux如何执行c程序,并获取命令输出内容。并且系统自带的system只能返回命令执行成功与否,不能捕获命令输出。
基于此,须要实现的需求有:
2.2扩充性
因为应用场景本就广泛,因而扩充性较好。
此函数可以执行任意命令,并捕获命令输出结果。
实际使用过程中可以把此函数作为最底层插口,之后层层封装,实现自己想要的功能。
2.3测试环境2.3.1Ubuntu
找到此方式时,我首先在Ubuntu中进行了测试,环境如下:
1zhaoc@ubuntu14:~$ lsb_release -a
2No LSB modules are available.
3Distributor ID: Ubuntu
4Description: Ubuntu 14.04.1 LTS
5Release: 14.04
6Codename: trusty
1zhaoc@ubuntu14:~$ 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/Linux
1gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1)
2.3.2工程代码
随即又放在工程代码中测试,环境如下:
1[root]#uname -a
2Linux itl 4.4.207+ #24 PREEMPT Fri Jan 29 18:09:37 CST 2021 armv5tejl GNU/Linux
1gcc version 4.8.3 20140320 (prerelease) (Sourcery CodeBench Lite 2014.05-29)
3函数原型
依据参考资料linux系统应用,优化后的函数原型如下
1#include
2#include
3
4#define CMD_RESULT_BUF_SIZE 1024
5
6/*
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 errorn", 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.
4
5 This function is a possible cancellation point and therefore not
6 marked with __THROW. */
7extern FILE *popen (const char *__command, const char *__modes) __wur;
8
9/* 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;
4函数封装
插口ExecuteCMD()对于基础的使用早已够了,并且输出结果是char*类型的linux运维最佳实践,在C++中实际使用上去不是很便捷,为何不直接转换为string类型呢?
假如转换为string类型,就可以使用C++标准库中的插口函数进行操作了。
于是简单封装了一下,此处的内联函数实际不一定会生效。
1/*
2 * 输入: 执行命令
3 * 输出: 命令执行结果字符串
4 */
5__inline std::string SystemWithResult(const char *cmd)
6{
7 char cBuf[CMD_RESULT_BUF_SIZE] = {0};
8 string sCmdResult;
9
10 ExecuteCMD(cmd, cBuf);
11 sCmdResult = string(cBuf); // char * 转换为 string 类型
12 printf("CMD Result: n%sn", sCmdResult.c_str());
13
14 return sCmdResult;
15}
5实际测试
使用ExecuteCMD()函数,进行测试,测试代码如下:
1#include
2#include
3
4#define CMD_RESULT_BUF_SIZE 1024
5
6/*
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 errorn", ps);
37 iRet = -1; // 处理失败
38 }
39
40 return iRet;
41}
42
43int main()
44{
45 char result[CMD_RESULT_BUF_SIZE]={0};
46
47 ExecuteCMD("ls -l", result);
48
49 printf("This is an examplenn");
50 printf("%s", result);
51 printf("nnThis is endn");
52
53 return 0;
54}
编译运行结果如下
1zhaoc@ubuntu14:~/test/11-shellCmdTest$ gcc test1.c
2zhaoc@ubuntu14:~/test/11-shellCmdTest$
3zhaoc@ubuntu14:~/test/11-shellCmdTest$
4zhaoc@ubuntu14:~/test/11-shellCmdTest$ ./a.out
5This is an example
6
7总用量 16
8-rwxrwxr-x 1 zhaoc zhaoc 8968 2月 2 19:27 a.out
9-rwxr--r-- 1 zhaoc zhaoc 1095 2月 2 19:27 test1.c
10
11
12This is end
13zhaoc@ubuntu14:~/test/11-shellCmdTest$
6总结
学会了一个车轮linux如何执行c程序,很开心。而且通过后续插口封装,可扩充性也挺好。重点还是C语言自己的库函数使用,例如popen()、pclose()、fgets()等。
假如文章内容有误,麻烦评论/私信多多指教!假如认为文章内容还不错,记得一键四连哦(点赞、收藏、留言、关注),倘若您能点个关注,那就是对我最大的鼓励,也将是我创作的动力,感谢您嘞!