quarta-feira, 15 de fevereiro de 2012

Capture idle "percentage" in C

This program will read /proc/stat an calculum the amount of time that computer was idle...


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#define BUFLEN 256
static char buf[BUFLEN];


int strsplit (char *string, char **fields, size_t size);

int main(void)
{
        FILE *stat;
        char *fields[9];        
        int numfields;

        unsigned int ncores;

        unsigned int idle;
        unsigned int old_idle = 0;

        
        while (1) {
                /*
                 * The cpu sum line SHOULD be the first line
                 * on /proc/stat, or things will get wrong.
                 */
                if ((stat = fopen("/proc/stat", "r")) == NULL) {
                        perror("fopen");
                        exit(EXIT_FAILURE);
                }

                fgets(buf, BUFLEN, stat);

                numfields = strsplit (buf, fields, 9);
                if (numfields < 5) {
                        fprintf(stderr, "To few fields\n");
                        exit(EXIT_FAILURE);
                }
                
                ncores = sysconf(_SC_NPROCESSORS_ONLN); /* number of cores */
                idle = atoi(fields[4]);
                printf("idle %d%%\n", (idle - old_idle) / ncores);
                old_idle = idle;
                
                fclose(stat);
                sleep(1);
        }                        

        return 0;
}

int strsplit (char *string, char **fields, size_t size)
{
        size_t i;
        char *ptr;
        char *saveptr;

        i = 0;
        ptr = string;
        saveptr = NULL;
        while ((fields[i] = strtok_r (ptr, " \t\r\n", &saveptr)) != NULL)
        {
                ptr = NULL;
                i++;

                if (i >= size)
                        break;
        }

        return ((int) i);
}