zoukankan      html  css  js  c++  java
  • C++使用shell命令

    #include <iostream>
    #include <stdio.h>
    #include <vector>
    #include <unistd.h>
    #include <sys/types.h>


    //execute shell command
    //执行一个shell命令,输出结果逐行存储在resvec中,并返回行数
    int32_t myexec(const char *cmd, std::vector<std::string> &resvec) {
        resvec.clear();
        FILE *pp = popen(cmd, "r"); //建立管道
        if (!pp) {
            return -1;
        }
        char tmp[1024]; //设置一个合适的长度,以存储每一行输出
        while (fgets(tmp, sizeof(tmp), pp) != NULL) {
            if (tmp[strlen(tmp) - 1] == ' ') {
                tmp[strlen(tmp) - 1] = ''; //去除换行符
            }
            resvec.push_back(tmp);
        }
        pclose(pp); //关闭管道
        return resvec.size();
    }

    int main(int argc, const char * argv[]) {
       
        std::vector<std::string> *vect = new std::vector<std::string>();
        pid_t pid = getpid();
        char *cmd = new char[1024];
        sprintf(cmd, "ps -p %d -o 'pid,pcpu,rss'",pid);
        std::cout<< cmd << std::endl;
        int32_t a = myexec(cmd, *vect);
       
        std::cout<< a << std::endl;
       
        int i = 0;
        int count = vect->size();
        for (; i < count; i++) {
            std::cout<< (*vect)[i] <<std::endl;
        }
       
        return 0;
    }

    include <iostream>
    #include <stdio.h>
    #include <vector>
    #include <unistd.h>
    #include <sys/types.h>


    //execute shell command
    //执行一个shell命令,输出结果逐行存储在resvec中,并返回行数
    int32_t myexec(const char *cmd, std::vector<std::string> &resvec) {
        resvec.clear();
        FILE *pp = popen(cmd, "r"); //建立管道
        if (!pp) {
            return -1;
        }
        char tmp[1024]; //设置一个合适的长度,以存储每一行输出
        while (fgets(tmp, sizeof(tmp), pp) != NULL) {
            if (tmp[strlen(tmp) - 1] == ' ') {
                tmp[strlen(tmp) - 1] = ''; //去除换行符
            }
            resvec.push_back(tmp);
        }
        pclose(pp); //关闭管道
        return resvec.size();
    }

    int main(int argc, const char * argv[]) {
       
        std::vector<std::string> *vect = new std::vector<std::string>();
        pid_t pid = getpid();
        char *cmd = new char[1024];
        sprintf(cmd, "ps -p %d -o 'pid,pcpu,rss'",pid);
        std::cout<< cmd << std::endl;
        int32_t a = myexec(cmd, *vect);
       
        std::cout<< a << std::endl;
       
        int i = 0;
        int count = vect->size();
        for (; i < count; i++) {
            std::cout<< (*vect)[i] <<std::endl;
        }
       
        return 0;
    }

  • 相关阅读:
    WordPress手机端插件——WPtouch
    WordPress404页面自定义
    WordPress浏览数插件的安装使用
    WordPress的SEO插件——WordPress SEO by yoast安装及使用
    WordPress友情链接插件的安装
    各大搜索引擎提交入口
    thinkphp博客项目纪录
    新概念英语第一册——视频
    ThinkPHP自定义错误页面、成功页面及异常页面
    豪情后台模板,图标大全
  • 原文地址:https://www.cnblogs.com/xubin-123/p/4307274.html
Copyright © 2011-2022 走看看