700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > linux c 通过 /proc 获取 pid 进程 列表

linux c 通过 /proc 获取 pid 进程 列表

时间:2018-12-09 17:16:36

相关推荐

linux c 通过 /proc 获取 pid 进程 列表

如果要获取当前正在运行的进程的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 + /statint 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);}return 0;}

样本输出:

1 (systemd) : 3735 (systemd-journal) : 166 (systemd-udevd): 291 (dbus-daemon) : 495 (systemd-logind) : 113 (dhclient): 243 (unattended-upgr) : 1048 (containerd) : 1151 (agetty) : 1..

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。