我需要从 /proc/PID/status
我试过这样做:
#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
最佳答案
/proc/[pid]/status
是一个文本文件。所以你的 fread
正在将文本复制到结构 status
- 所以一切看起来都是乱码。
您可以逐行读取状态文件,也可以使用 /proc/[pid]/stat
文件,该文件在一行中包含相同的信息(status
供人类使用,而 stat
供程序使用)。要获取进程 ID(或任何其他信息),您只需对该单行进行标记。
关于c - 从/proc/<pid>/status 获取 pid 和其他进程信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21089956/