【问题标题】:Getting pid and other process information from /proc/<pid>/status从 /proc/<pid>/status 获取 pid 和其他进程信息
【发布时间】:2014-01-13 11:18:31
【问题描述】:

我需要从/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

【问题讨论】:

  • 你尝试过从 shell cat /proc/$$/status 吗?正如您将看到的,它是一个文本文件,而不是二进制文件,因此您应该一次读取一行,并将其解析为文本。这里的prstatus_t 没用。

标签: c linux


【解决方案1】:

问题是/proc/[pid]/status 是一个文本文件。所以你的fread 正在将文本复制到结构status 中——所以一切看起来都像胡言乱语。

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

【讨论】:

    猜你喜欢
    • 2015-12-15
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    相关资源
    最近更新 更多