markizano

loadavg.c

Oct 2nd, 2012
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.93 KB | None | 0 0
  1.  
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <errno.h>
  6. #include <error.h>
  7. #include <string.h>
  8.  
  9. #define GREEN 0.45
  10. #define YELLOW 0.80
  11. #define RED 1
  12.  
  13. // long sysconf(int name);
  14. // int getloadavg(double loadavg[], int nelm);
  15.  
  16. int main () {
  17.     long n_cpu;
  18.     double loadavg[3];
  19.     char la[3][32], *prefix;
  20.     int i;
  21.  
  22.     memset(la[0], 0, sizeof la[0]);
  23.     memset(la[1], 0, sizeof la[1]);
  24.     memset(la[2], 0, sizeof la[2]);
  25. //  memset(prefix, 0, sizeof prefix);
  26.  
  27. #ifdef _SC_NPROCESSORS_ONLN
  28.     if ( ( n_cpu = sysconf(_SC_NPROCESSORS_CONF) ) < 0 ) {
  29.         fprintf(stderr, "Could not get number of processors: %m\n");
  30.         return errno;
  31.     }
  32.     if ( n_cpu == 0 ) {
  33.         fprintf(stderr, "We have 0 processors?!\n");
  34.         return 1;
  35.     }
  36.  
  37.     if ( getloadavg(loadavg, 3) < 0 ) {
  38.         fprintf(stderr, "Could not get load average: %m\n");
  39.         return errno;
  40.     }
  41.  
  42.     for ( i = 0; i <= 2; ++i ) {
  43.         if ( ( loadavg[i] / n_cpu >= 0 ) && ( loadavg[i] / n_cpu <= GREEN ) ) {
  44.             if ( ( prefix = strndup("32", 2) ) == NULL ) {
  45.                 fprintf(stderr, "Could not allocate space for prefix.");
  46.             }
  47.         } else if ( ( loadavg[i] / n_cpu >= GREEN ) && ( loadavg[i] / n_cpu <= YELLOW ) ) {
  48.             if ( ( prefix = strndup("33", 2) ) == NULL ) {
  49.                 fprintf(stderr, "Could not allocate space for prefix.");
  50.             }
  51.         } else if ( ( loadavg[i] / n_cpu >= YELLOW ) && ( loadavg[i] / n_cpu <= RED ) ) {
  52.             if ( ( prefix = strndup("31", 2) ) == NULL ) {
  53.                 fprintf(stderr, "Could not allocate space for prefix.");
  54.             }
  55.         } else if ( loadavg[i] / n_cpu < RED ) {
  56.             if ( ( prefix = strndup("31;01", 5) ) == NULL ) {
  57.                 fprintf(stderr, "Could not allocate space for prefix.");
  58.             }
  59.         } else {
  60.             prefix = strndup("00", 2);
  61.         }
  62.  
  63.         sprintf(la[i], "\033[%sm%0.2f\033[00m", prefix, loadavg[i]);
  64.         free(prefix);
  65.     }
  66.  
  67.     printf("%s,%s,%s\n", la[0], la[1], la[2]);
  68.     return 0;
  69. #else
  70.     fprintf(stderr, "Could not get number of processors on a non-standard system.\n");
  71.     return 1;
  72. #endif
  73. }
Advertisement
Add Comment
Please, Sign In to add comment