道阻且长,行则将至。埋头苦干,不鸣则已,一鸣惊人!加油,骚年!
祝大家新年快乐,身体健康,工作顺利,牛年大吉!
1、【c/c++】如何调用【linux】shell命令行命令并获取命令行的输出内容(https://blog.csdn.net/youngstar70/article/details/70305687)
最近在实际程序开发中,需要通过程序执行 shell 命令,并获取命令输出内容。但是系统自带的 system 只能返回命令执行成功与否,不能捕获命令输出。
基于此,需要实现的需求有:
由于应用场景本就广泛,因此扩展性较好。
此函数可以执行任意命令,并捕获命令输出结果。
实际使用过程中可以把此函数作为最底层接口,然后层层封装,实现自己想要的功能。
找到此方法时,我首先在 Ubuntu 中进行了测试,环境如下:
zhaoc@ubuntu14:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 14.04.1 LTS
Release: 14.04
Codename: trusty
zhaoc@ubuntu14:~$ uname -a
Linux 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
gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1)
随后又放到工程代码中测试,环境如下:
[root]#uname -a
Linux itl 4.4.207+ #24 PREEMPT Fri Jan 29 18:09:37 CST 2021 armv5tejl GNU/Linux
gcc version 4.8.3 20140320 (prerelease) (Sourcery CodeBench Lite 2014.05-29)
根据参考资料,优化后的函数原型如下
#include
#include
#define CMD_RESULT_BUF_SIZE 1024
/*
* cmd:待执行命令
* result:命令输出结果
* 函数返回:0 成功;-1 失败;
*/
int ExecuteCMD(const char *cmd, char *result)
{
int iRet = -1;
char buf_ps[CMD_RESULT_BUF_SIZE];
char ps[CMD_RESULT_BUF_SIZE] = {
0};
FILE *ptr;
strcpy(ps, cmd);
if((ptr = popen(ps, "r")) != NULL)
{
while(fgets(buf_ps, sizeof(buf_ps), ptr) != NULL)
{
strcat(result, buf_ps);
if(strlen(result) > CMD_RESULT_BUF_SIZE)
{
break;
}
}
pclose(ptr);
ptr = NULL;
iRet = 0; // 处理成功
}
else
{
printf("popen %s error\n", ps);
iRet = -1; // 处理失败
}
return iRet;
}
查看源码中的 popen() 、pclose() 函数原型定义如下:
#if (defined __USE_POSIX2 || defined __USE_SVID || defined __USE_BSD || \
defined __USE_MISC)
/* Create a new stream connected to a pipe running the given command.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern FILE *popen (const char *__command, const char *__modes) __wur;
/* Close a stream opened by popen and return the status of its child.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern int pclose (FILE *__stream);
#endif
查看源码中的 fgets() 函数原型如下:
/* Get a newline-terminated string of finite length from STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern char *fgets (char *__restrict __s, int __n, FILE *__restrict __stream)
__wur;
接口 ExecuteCMD() 对于基础的使用已经够了,但是输出结果是 char * 类型的,在 C++ 中实际使用起来不是很方便,为什么不直接转换为 string 类型呢?
如果转换为 string 类型,就可以使用 C++ 标准库中的接口函数进行操作了。
于是简单封装了一下,此处的内联函数实际不一定会生效。
/*
* 输入: 执行命令
* 输出: 命令执行结果字符串
*/
__inline std::string SystemWithResult(const char *cmd)
{
char cBuf[CMD_RESULT_BUF_SIZE] = {0};
string sCmdResult;
ExecuteCMD(cmd, cBuf);
sCmdResult = string(cBuf); // char * 转换为 string 类型
printf("CMD Result: \n%s\n", sCmdResult.c_str());
return sCmdResult;
}
使用 ExecuteCMD() 函数,进行测试,测试代码如下:
#include
#include
#define CMD_RESULT_BUF_SIZE 1024
/*
* cmd:待执行命令
* result:命令输出结果
* 函数返回:0 成功;-1 失败;
*/
int ExecuteCMD(const char *cmd, char *result)
{
int iRet = -1;
char buf_ps[CMD_RESULT_BUF_SIZE];
char ps[CMD_RESULT_BUF_SIZE] = {
0};
FILE *ptr;
strcpy(ps, cmd);
if((ptr = popen(ps, "r")) != NULL)
{
while(fgets(buf_ps, sizeof(buf_ps), ptr) != NULL)
{
strcat(result, buf_ps);
if(strlen(result) > CMD_RESULT_BUF_SIZE)
{
break;
}
}
pclose(ptr);
ptr = NULL;
iRet = 0; // 处理成功
}
else
{
printf("popen %s error\n", ps);
iRet = -1; // 处理失败
}
return iRet;
}
int main()
{
char result[CMD_RESULT_BUF_SIZE]={
0};
ExecuteCMD("ls -l", result);
printf("This is an example\n\n");
printf("%s", result);
printf("\n\nThis is end\n");
return 0;
}
编译运行结果如下
zhaoc@ubuntu14:~/test/11-shellCmdTest$ gcc test1.c
zhaoc@ubuntu14:~/test/11-shellCmdTest$
zhaoc@ubuntu14:~/test/11-shellCmdTest$
zhaoc@ubuntu14:~/test/11-shellCmdTest$ ./a.out
This is an example
总用量 16
-rwxrwxr-x 1 zhaoc zhaoc 8968 2月 2 19:27 a.out
-rwxr--r-- 1 zhaoc zhaoc 1095 2月 2 19:27 test1.c
This is end
zhaoc@ubuntu14:~/test/11-shellCmdTest$
学会了一个车轮,很开心。并且通过后续接口封装,可扩展性也很好。重点还是 C 语言自己的库函数使用,比如 popen() 、pclose() 、fgets() 等。
如果文章内容有误,麻烦评论/私信多多指教!如果觉得文章内容还不错,记得一键四连哦(点赞、收藏、留言、关注),如果您能点个关注,那就是对我最大的鼓励,也将是我创作的动力,谢谢您嘞!