2014-01-13 1 views
1
내가 /proc/PID/status

에서 PID 및 기타 프로세스 정보를 얻기/proc 디렉토리/<pid>/상태

내가 가지고에서 (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

'cat/proc/$$/status' 쉘에서 시도 했습니까? 보시다시피 이진 파일이 아닌 텍스트 파일이므로 한 번에 한 줄씩 읽고 텍스트로 파싱해야합니다. 'prstatus_t'는 쓸모가 없습니다. – rodrigo

답변

1

것은이 /proc/[pid]/status 인 텍스트 파일입니다 이런 식으로 할 노력했다. 따라서 fread은 텍스트를 status 구조체에 복사하므로 모든 것이 횡설수설처럼 보입니다.

당신은 라인으로 상태 파일 라인을 읽을 수 또는 당신은 한 줄에 동일한 정보를 (stat이 프로그램 consumtion입니다 동안 status이 인간의 소비를위한)이 포함 된 /proc/[pid]/stat 파일을 사용할 수 있습니다. 프로세스 ID (또는 다른 정보)를 얻으려면 해당 단일 행을 토큰 화해야합니다.