linux 下获取进程ID 和 进程名

    技术2022-05-20  49

    最近在学进程间通信,但是我一直没找到一个linux 自带的可以根据进程名来获取进程ID的函数,于是就自己写了一个。可以获取到正确的结果,但是是通过system函数,然后 读取文件获得的,效率不高。如果高人看见来,有什么好的建议请提醒我,谢谢。

     

    //GetProcessAttr.h/// #include <stdio.h> #include <stdlib.h> #include <iostream> #include <string.h> #include <iostream> #include <fcntl.h> #include <sys/types.h> class GetProcessAttr { public:     GetProcessAttr();     ~GetProcessAttr();     //根据进程名,获取进程ID     int getProcessId(char *process_name);     //根据进程ID,获取进程名字     char* getProcessName(int process_id); };

     

     

    ///GetProcessAttr.cpp

     

    #include "GetProcessAttr.h" GetProcessAttr::GetProcessAttr() { } GetProcessAttr::~GetProcessAttr() { } int GetProcessAttr::getProcessId(char *process_name) {     //get process id by shell     char cmd[100]={0};     sprintf(cmd,"pidof %s > pid.txt",process_name);     system(cmd);         //open file     int fd=open("pid.txt" ,O_RDWR);     if(fd<0)     {         perror("open file failed/n");         system("rm pid.txt");         return -1;     }     //read file     char read_buf[50]={0};        if(read(fd,read_buf,50)<0)     {         perror("read():");         close(fd)         system("rm pid.txt");         return -1;     }         //close file     if(close(fd)<0)     {         perror("close():");         system("rm pid.txt");         return -1;     }     //remove file     system("rm pid.txt");     return atoi(read_buf); } char* GetProcessAttr::getProcessName(int process_id) {     //get process name by shell     char cmd[100]={0};     sprintf(cmd,"readlink /proc/%d/exe >pname.txt",process_id);     system(cmd);         //open file     int fd=open("pname.txt" ,O_RDWR);     if(fd<0)     {         perror("open():/n");         return NULL;     }     //read file     char *pname = new char[200];        if(read(fd,pname,200)<0)     {         perror("read():");         return NULL;     }         //close file     if(close(fd)<0)     {         perror("close():");         return NULL;     }     //remove file     system("rm pname.txt");     return pname; }


    最新回复(0)