1. 程式人生 > >linux中通過proc獲取程序名以及PID

linux中通過proc獲取程序名以及PID

背景 

     給定某個執行緒的執行緒號tid,獲取對應的程序名,或通過程序號獲取程序名。

原始碼(通過程序名獲取程序號):

 void getNameByPid(pid_t pid, char *task_name) {
     char proc_pid_path[BUF_SIZE];
     char buf[BUF_SIZE];

     sprintf(proc_pid_path, "/proc/%d/status", pid);
     FILE* fp = fopen(proc_pid_path, "r");
     if(NULL != fp){
         if( fgets(buf, BUF_SIZE-1, fp)== NULL ){
             fclose(fp);
         }
         fclose(fp);
         sscanf(buf, "%*s %s", task_name);
     }
 }

原始碼(通過程序號獲取程序名):

void getPidByName(pid_t *pid, char *task_name)
 {
     DIR *dir;
     struct dirent *ptr;
     FILE *fp;
     char filepath[50];
     char cur_task_name[50];
     char buf[BUF_SIZE];

     dir = opendir("/proc"); 
     if (NULL != dir)
     {
         while ((ptr = readdir(dir)) != NULL) //迴圈讀取/proc下的每一個檔案/資料夾
         {
             //如果讀取到的是"."或者".."則跳過,讀取到的不是資料夾名字也跳過
             if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0))
                 continue;
             if (DT_DIR != ptr->d_type)
                 continue;

             sprintf(filepath, "/proc/%s/status", ptr->d_name);//生成要讀取的檔案的路徑
             fp = fopen(filepath, "r");
             if (NULL != fp)
             {
                 if( fgets(buf, BUF_SIZE-1, fp)== NULL ){
                     fclose(fp);
                     continue;
                 }
                 sscanf(buf, "%*s %s", cur_task_name);

                 //如果檔案內容滿足要求則列印路徑的名字(即程序的PID)
                 if (!strcmp(task_name, cur_task_name)){
                     sscanf(ptr->d_name, "%d", pid);
                 }
                 fclose(fp);
             }
         }
         closedir(dir);
     }
 }