linux下进程号,Linux下C++获取进程号

如何在Linux下通过C++程序获取ps -ef | grep “****” 的执行结果,并分解其中的进程号,废话少说,直接上代码:

#include

#include

#include

#include

#include

#include

#include

using namespace std;

map pmap;

int prep_map(map &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::value_type(iPID_str,strPInfo.c_str()));

}

printf("pInfo = %s \n", strPInfo.c_str());

}

pclose(pstr);

return 1;

}

int main()

{

prep_map(pmap);

map::iterator it;

for(it = pmap.begin();it != pmap.end();it++)

{

cout << "---pid is : " << it->first << endl;

cout << "---cmd is : " << it->second << endl;

}

}0b1331709591d260c1c78e86d0c51c18.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值