c++shellコマンドの使用
4406 ワード
#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] = '\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;
}