Linux下C++获取进程号


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

#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; 
    } 

相关内容