要在 Linux 裡用 C++ 取得「等同 ps -ef | grep "****" 的結果」,並從中抽出 PID 與命令內容,最直覺的做法就是借 shell 之手:用 popen 開一條管道,把 ps、grep、awk 串起來,再逐行解析。廢話少說,直接看程式:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string>
#include <map>
#include <cstdlib>
#include <iostream>
using namespace std;
map<string,string> pmap;
int prep_map(map<string,string> &pmap){
FILE *pstr;
char cmd[128],buff[512],*p;
int iPID;
const char *name = "mongod"; // 要查找的進程名
int pidPosition = 1;
int pInfoPosition = 7;
memset(cmd,0,sizeof(cmd));
sprintf(cmd, "ps -ef | grep mongod | grep -v \"grep\" | grep fork | awk '{printf $2;printf \"|\";for(i=8;i<=NF;i++)printf\"%s \",$i;printf\"\\n\"}'", name);
pstr = popen(cmd, "r");
if(pstr == NULL) { return 1; }
memset(buff,0,sizeof(buff));
while( 1 )
{
fgets(buff,512,pstr);
if(feof(pstr)) { break; }
printf("buffer=%s",buff);
p = strtok(buff, " ");
int iPos = 0;
string strPInfo;
while(NULL != p)
{
if(pidPosition == iPos) {
iPID = atoi(p);
printf("pid=%d \n", iPID);
}
if(iPos >= pInfoPosition) {
strPInfo += p;
strPInfo += " ";
}
iPos++;
p = strtok(NULL, " ");
string iPID_str = iPID+"";
pmap.insert(map<string,string>::value_type(iPID_str, strPInfo.c_str()));
}
printf("pInfo = %s \n", strPInfo.c_str());
}
pclose(pstr);
return 1;
}
int main()
{
prep_map(pmap);
map<string,string>::iterator it;
for(it = pmap.begin(); it != pmap.end(); it++)
{
cout << "---pid is : " << it->first << endl;
cout << "---cmd is : " << it->second << endl;
}
}
命令中 grep -v "grep" 是為了濾掉 grep 自己那一列,grep fork 則用來鎖定以 fork 模式啟動的 mongod;awk 段落把第 2 欄(PID)與第 8 欄之後的內容用 | 串起來輸出,讓後續解析有明確的分隔依據。
C++ 這邊以 strtok 切欄位,用 pidPosition 抓 PID、pInfoPosition 之後的內容併成命令字串,最後存進 map,讓「PID → 命令」的對應關係一目了然。實務上要留意:popen 字串若帶入外部輸入,需做好跳脫以避免命令注入;另外 feof 的用法在邊界上略嫌危險,正式環境建議改成檢查 fgets 的傳回值。