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] == '\n') {
            tmp[strlen(tmp) - 1] = '\0'; //去除換行符
        }
        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] == '\n') {
            tmp[strlen(tmp) - 1] = '\0'; //去除換行符
        }
        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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM