Programmatically read all the processes status from /proc

16,894

Solution 1

In Linux process status is saved in /proc/PID/status pseudo-file and represented in textual form (other OS have completely different structure of their procfs):

$ grep State /proc/self/status
State:  R (running)

So you need a "parser" for that file:

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);
}

To read all processes you have to use opendir()/readdir()/closedir() and open only directories that have numerical characters (other are sysctl variables, etc.):

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);

Alternatively, you may use procps tools which already implemented it.

Solution 2

This snippet below invokes two C programs that do just that:

find /proc -maxdepth 2 -wholename '/proc/[0-9]*/status'  | xargs cat
Share:
16,894
Lily
Author by

Lily

Updated on August 25, 2022

Comments

  • Lily
    Lily over 1 year

    I want to save all of the running processes' status from the /proc folder in a file. After reading some questions and answers here I think I should use the pstatus struct to determine which fields I want to save (correct me if I'm wrong?), but I don't know how I can efficiently loop through all of the running processes.

  • PSkocik
    PSkocik about 9 years
    Though, to be honest, a third C program in the form of a shell is required to spawn the above C programs and set up the pipe between them.
  • Lily
    Lily about 9 years
    Thank you very much! I think this will help a lot.