aboutsummaryrefslogtreecommitdiffstats
path: root/plugin_meminfo.c
blob: b455f7199f08901b5b290957b1533d4b0f7a1a10 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
generated by cgit v1.2.3 (git 2.25.1) at 2024-12-17 04:16:37 +0000
 


an class="cm"> */

/* 
 * exported functions:
 *
 * int plugin_init_meminfo (void)
 *  adds functions to access /proc/meminfo
 *
 */


#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>

#include "debug.h"
#include "plugin.h"

#include "hash.h"


static HASH MemInfo = { 0, };


static int parse_meminfo (void)
{
  int age;
  int line;
  FILE *stream;
  
  // reread every 100 msec only
  age=hash_age(&MemInfo, NULL, NULL);
  if (age>0 && age<=100) return 0;
  
  stream=fopen("/proc/meminfo", "r");
  if (stream==NULL) {
    error ("fopen(/proc/meminfo) failed: %s", strerror(errno));
    return -1;
  }
    
  line=0;
  while (!feof(stream)) {
    char buffer[256];
    char *c, *key, *val;
    fgets (buffer, sizeof(buffer), stream);
    c=strchr(buffer, ':');
    if (c==NULL) continue;
    key=buffer; val=c+1;
    // strip leading blanks from key
    while (isspace(*key)) *key++='\0';
    // strip trailing blanks from key
    do *c='\0'; while (isspace(*--c));
    // strip leading blanks from value
    while (isspace(*val)) *val++='\0';
    // strip trailing blanks from value
    for (c=val; *c!='\0';c++);
    while (isspace(*--c)) *c='\0';
    // skip lines that do not end with " kB"
    if (*c=='B' && *(c-1)=='k' && *(c-2)==' ') {
      // strip trailing " kB" from value
      *(c-2)='\0';
      // add entry to hash table
      hash_set (&MemInfo, key, val);
    }
  }
  fclose (stream);
  return 0;
}  

static void my_meminfo (RESULT *result, RESULT *arg1)
{
  char *key, *val;
  
  if (parse_meminfo()<0) {
    SetResult(&result, R_STRING, ""); 
    return;
  }
  
  key=R2S(arg1);
  val=hash_get(&MemInfo, key);
  if (val==NULL) val="";
  
  SetResult(&result, R_STRING, val); 
}


int plugin_init_meminfo (void)
{
  AddFunction ("meminfo", 1, my_meminfo);
  return 0;
}