c - 从/proc/<pid>/status 获取 pid 和其他进程信息

标签 c linux

我需要从 /proc/PID/status

获取一些信息(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

最佳答案

/proc/[pid]/status 是一个文本文件。所以你的 fread 正在将文本复制到结构 status - 所以一切看起来都是乱码。

您可以逐行读取状态文件,也可以使用 /proc/[pid]/stat 文件,该文件在一行中包含相同的信息(status 供人类使用,而 stat 供程序使用)。要获取进程 ID(或任何其他信息),您只需对该单行进行标记。

关于c - 从/proc/<pid>/status 获取 pid 和其他进程信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21089956/

相关文章:

php - 如何通过 PKCS5_PBKDF2_HMAC 和 hash_hmac 在 C 和 php 中获得相同的输出

c - 以下语句中的单个 & 是什么意思?

c++ - ‘.’ token 之前应有非限定 ID

linux - 将空格视为 n 列后的空格

linux - 访问 apache AWS EC2 Linux 服务器上的错误日志

c - 声明一个同时具有寄存器和静态存储类的变量

C:程序在完成 for 循环之前崩溃

c - 我是否必须在 'longjmp' 之后调用 'setjmp'

java - 以另一个用户身份加载进程?

linux - ZFS 显示可用空间,无法删除