c - 在 Linux 中从/proc 获取 PID 列表

标签 c linux pid procfs

我正在制作一个程序,可以查看某些进程中是否发生页面错误,
我的方法是获取所有进程的 PID 并查看 rss , maj_flt等通过在每一个 /proc/[PID] 中寻找, 检查总数是否有变化 maj_flt .
但是为了获取所有正在运行的进程的 PID,我需要直接从我的 C 程序中获取它们,而不使用像 ps 这样的现有 shell 命令。 , top等等。
有谁知道正在运行的PID数据在/proc中的位置吗?或者别的地方?或者如果有另一种方法可以做到这一点,比如通过我的 C 程序中的系统调用函数来获取它?

最佳答案

不幸的是,没有公开 PID 列表的系统调用。在 Linux 中您应该通过 /proc 获取此信息的方式。虚拟文件系统。
如果您想要当前正在运行的进程的 PID 列表,您可以使用 opendir() readdir() 打开/proc并遍历其中的文件/文件夹列表。然后,您可以检查文件名是数字的文件夹。检查后,您可以打开/proc/<PID>/stat获取您想要的信息(特别是,您需要第 12 个字段 majflt )。
这是一个简单的工作示例(可能需要进行更多错误检查和调整):

#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <ctype.h>

// Helper function to check if a struct dirent from /proc is a PID folder.
int is_pid_folder(const struct dirent *entry) {
    const char *p;

    for (p = entry->d_name; *p; p++) {
        if (!isdigit(*p))
            return 0;
    }

    return 1;
}

int main(void) {
    DIR *procdir;
    FILE *fp;
    struct dirent *entry;
    char path[256 + 5 + 5]; // d_name + /proc + /stat
    int pid;
    unsigned long maj_faults;

    // Open /proc directory.
    procdir = opendir("/proc");
    if (!procdir) {
        perror("opendir failed");
        return 1;
    }

    // Iterate through all files and folders of /proc.
    while ((entry = readdir(procdir))) {
        // Skip anything that is not a PID folder.
        if (!is_pid_folder(entry))
            continue;

        // Try to open /proc/<PID>/stat.
        snprintf(path, sizeof(path), "/proc/%s/stat", entry->d_name);
        fp = fopen(path, "r");

        if (!fp) {
            perror(path);
            continue;
        }

        // Get PID, process name and number of faults.
        fscanf(fp, "%d %s %*c %*d %*d %*d %*d %*d %*u %*lu %*lu %lu",
            &pid, &path, &maj_faults
        );

        // Pretty print.
        printf("%5d %-20s: %lu\n", pid, path, maj_faults);
        fclose(fp);
    }

    closedir(procdir);
    return 0;
}
示例输出:
    1 (systemd)           : 37
   35 (systemd-journal)   : 1
   66 (systemd-udevd)     : 2
   91 (dbus-daemon)       : 4
   95 (systemd-logind)    : 1
  113 (dhclient)          : 2
  143 (unattended-upgr)   : 10
  148 (containerd)        : 11
  151 (agetty)            : 1
  ...

关于c - 在 Linux 中从/proc 获取 PID 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63372288/

相关文章:

c - 当我将指向 unsigned int 的指针转换为 unsigned long long 指针时,为什么我会看到一个更大的值?

c++ - 如何使用指针和长度未知遍历数组?

linux - 在 Linux 上安装 tar.gz

bash - Cygwin:如何获取由 CygStart 启动的程序的 PID?

c - 为什么函数会根据容量返回不同的值

c - 从 perf 获取用户空间堆栈信息

java - é 未正确解析

realpath 函数的转换问题(C 编程)

java - 如何获取生成的 Java 进程的 PID

linux - jira服务宕机时自动重启