2014-01-13 44 views
1

我需要得到一些信息(PID僅僅是一個例子,我知道它很容易得到它在許多其他方面)從/proc/PID/status從獲取PID和其他處理信息的/ proc/<pid> /狀態

我有試圖做這種方式:

#include <stdio.h> 
#include <unistd.h> 
#include <stdlib.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <string.h> 
#include <fcntl.h> 
#include <sys/procfs.h> 
#include <sys/signal.h> 
#include <sys/syscall.h> 
#include <sys/param.h> 

int main(){ 
     char buf[BUFSIZ], buffer[10]; 
     char pathbase[20], pathdir[20]; 
     FILE *fp; 
     prstatus_t status; 

     printf("Process ID: %d\n", getpid()); 
     printf("Parent process ID: %d\n", getppid()); 
     printf("Group ID: %d\n", getpgrp()); 
     printf("Session ID: %d\n", getsid(0)); 

     strcpy(pathbase,"/proc/"); 
     sprintf(buffer, "%d", getpid()); 
     strcat(pathbase, buffer); 

     strcpy(pathdir, pathbase); 
     strcat(pathdir,"/status"); 

     if((fp = fopen(pathdir, "r")) == NULL) perror("fopen"); 
     fread(&status, sizeof(prstatus_t), 1, fp); 

     printf("Proces id: %d\n", status.pr_pid); 
     printf("Proces ppid: %d\n", (int)status.pr_ppid); 
     fclose(fp); 
} 

,它顯然是錯誤的,導致的結果我得到的是:

Process ID: 5474 
Parent process ID: 3781 
Group ID: 5474 
Session ID: 3781 
Proces id: 1735289198 
Proces ppid: 1733560873 
+1

你嘗試從shell'cat/proc/$$/status'嗎?如你所見,它是一個文本文件,不是二進制文件,所以你應該一次讀一行,並將其解析爲文本。這裏的'prstatus_t'沒有用處。 – rodrigo

回答

1

的事情是/proc/[pid]/status是一個文本文件。因此,您的fread正在將文本複製到結構status - 因此,所有內容都將看起來像亂碼。

您可以逐行讀取狀態文件,也可以使用單行上包含相同信息的/proc/[pid]/stat文件(status用於人類消耗,而stat用於程序消耗)。要獲得進程ID(或任何其他信息),您只需標記該單行。

相關問題