Chulainn
Chulainn

Reputation: 11

(Ubuntu) C Computing CPU usage using /proc/stat

I'm trying to write a program in C that will read from /proc/stat, wait a second, then read from /proc/stat again a second later, then do some math to find the "current" CPU usage, as well as the usage for each core. I think that the easiest way to do this is to save the results of /proc/stat to a file, as well as a second file for the second "state" of /proc/stat. I would then read from it and calculate from there. For some reason, though, I have no clue why neither of my files are being created.

int main() {
    FILE *state0;
    FILE *state1;
    state0 = fopen("/proc/stat", "w+");
    delay();
    state1 = fopen("/proc/stat", "w+");

    char *con0 = malloc(500);
    fprintf(state0, con0);

    fclose(state0);
    fclose(state1);

    return 0;
}

And help is greatly appreciated

Upvotes: 0

Views: 165

Answers (1)

Green-Avocado
Green-Avocado

Reputation: 891

The issue is, when you try to save a file by calling:

fprintf(state0, con0);

You're trying to write the memory allocated at con0 to state0, which is a pointer to /proc/stat.

This of course fails because you don't have permissions to write to /proc/stat, which you shouldn't.

To open these files for reading, as tadman mentioned, you want to open the files in "r" mode:

FILE *state0;
FILE *state1;
state0 = fopen("/proc/stat", "r");
delay();
state1 = fopen("/proc/stat", "r");

What you'd want to do is create a separate file, for example:

FILE *newfile;
newfile = fopen("/tmp/procstattemp", "w");

and write to this file using:

fprintf(newfile, con0);

Also, you're allocating memory for con0, but you haven't written anything to this buffer. If you want to save /proc/stat to a file, you'll need to read the file and copy it into con0 before writing your temporary file.

See also:

http://www.cplusplus.com/reference/cstdio/fprintf/

http://www.cplusplus.com/reference/cstdio/fopen/

Upvotes: 1

Related Questions