您的位置:首页 > 运维架构 > Shell

【c/c++】如何调用【linux】shell命令行命令并获取命令行的输出内容

2017-04-20 21:37 766 查看
#include <stdio.h>
#include <string.h>

void executeCMD(const char *cmd, char *result)
{
char buf_ps[1024];
char ps[1024]={0};
FILE *ptr;
strcpy(ps, cmd);
if((ptr=popen(ps, "r"))!=NULL)
{
while(fgets(buf_ps, 1024, ptr)!=NULL)
{
//	       可以通过这行来获取shell命令行中的每一行的输出
//	   	   printf("%s", buf_ps);
strcat(result, buf_ps);
if(strlen(result)>1024)
break;
}
pclose(ptr);
ptr = NULL;
}
else
{
printf("popen %s error\n", ps);
}
}

int main()
{
char result[1024]={0};
executeCMD("python /usr/xhh/pythonprojects/Demo1.py [1,2,3]", result);
//      这行是将每一行的输出拼接之后获取到了result字符串中了
printf("%s", result);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: