gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:05:27 26 4
gpt4 key购买 nike

我正在制作一个程序,可以查看某些进程中是否发生页面错误,
我的方法是获取所有进程的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com