C++执行shell命令获取结果

121次阅读
没有评论

共计 478 个字符,预计需要花费 2 分钟才能阅读完成。

c++可以通过系统调用的方式执行shell命令

#include <cstdlib>
int main()
{   
    system("ps -ef| grep myprocess");

    return 0;
}

但是如果要获取命令的执行结果,那么就需要

使用

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <cstring>
using namespace std;
int executeCMD(const char *cmd,char *result)
{
    char buf_ps[512];
    char ps[512]={0};
    int len=0;
    FILE *ptr;
    strcpy(ps, cmd);
    if((ptr=popen(ps, "r"))!=NULL)
    {
        while(fgets(buf_ps, 512, ptr)!=NULL)
        {
           strcat(result, buf_ps);
           if(strlen(result)>512)
               break;
        }
        pclose(ptr);
        ptr = NULL;
    }
    else
    {
        printf("popen %s error\n", ps);
    }
}
正文完
 
admin
版权声明:本站原创文章,由 admin 2021-09-17发表,共计478字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码