以编程方式从/ proc读取所有进程状态

Lil*_*ily 2 c linux ubuntu

我想使用/ proc文件夹将所有正在运行的进程状态保存在文件中.从这里阅读一些问题和答案我认为我应该使用pstatus结构来确定我想保存哪些字段(如果我错了,请纠正我?)但我不知道如何有效地循环所有正在运行的进程.

mya*_*aut 10

在Linux中,进程状态保存在/proc/PID/status伪文件中并以文本形式表示(其他操作系统的procfs结构完全不同):

$ grep State /proc/self/status
State:  R (running)
Run Code Online (Sandbox Code Playgroud)

所以你需要一个"解析器"来存储该文件:

void print_status(long tgid) {
    char path[40], line[100], *p;
    FILE* statusf;

    snprintf(path, 40, "/proc/%ld/status", tgid);

    statusf = fopen(path, "r");
    if(!statusf)
        return;

    while(fgets(line, 100, statusf)) {
        if(strncmp(line, "State:", 6) != 0)
            continue;
        // Ignore "State:" and whitespace
        p = line + 7;
        while(isspace(*p)) ++p;

        printf("%6d %s", tgid, p);
        break;
    }

    fclose(statusf);
}
Run Code Online (Sandbox Code Playgroud)

要了解你要使用的所有进程opendir()/ readdir()/ closedir()打开只有具有数字字符(其他都sysctl开关等)的目录:

DIR* proc = opendir("/proc");
struct dirent* ent;
long tgid;

if(proc == NULL) {
    perror("opendir(/proc)");
    return 1;
}

while(ent = readdir(proc)) {
    if(!isdigit(*ent->d_name))
        continue;

    tgid = strtol(ent->d_name, NULL, 10);

    print_status(tgid);
}

closedir(proc);
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用已经实现它的procps工具.