File: passive_memory.c

package info (click to toggle)
nws 2.11-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 2,700 kB
  • ctags: 2,820
  • sloc: ansic: 28,849; sh: 3,289; java: 1,205; makefile: 697; perl: 12
file content (101 lines) | stat: -rwxr-xr-x 2,224 bytes parent folder | download
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/* $Id: passive_memory.c,v 1.18 2004/08/26 01:07:47 graziano Exp $ */

#include "config_nws.h"

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

#include "diagnostic.h"
#include "memory.h"
#include "osutil.h"


/* returns the free memory. 0 on error */
static double
getFreeMem() {
	double bytesBuffer;
	double bytesCache;
	double bytesFree;
	double ret;
	FILE *file;
	char line[511 + 1];

	ret = 0;
	bytesFree = bytesBuffer = bytesCache = -1;

	/* we try to read /proc/meminfo first: it's more accurate and
	 * faster */
	file = fopen("/proc/meminfo", "r");
	if (file != NULL) {
		/* we are on business: we need to look for few tags:
		 * MemFree, Buffers and Cached */
		while(fgets(line, sizeof(line), file) != NULL) {
			if (line[0] == ' ') {
				/* skip empty lines */
				continue;
			}
			if (!strncmp(line, "MemFree", strlen("MemFree"))) {
				/* we got the free mem */
				if (!sscanf(line, "%*s %lf", &bytesFree)) {
					bytesFree = -1;
				}
			} 
			if (!strncmp(line, "Buffers", strlen("Buffers"))) {
				/* we got the buffers */
				if (!sscanf(line, "%*s %lf", &bytesBuffer)) {
					bytesBuffer = -1;
				}
			} 
			if (!strncmp(line, "Cached", strlen("Cached"))) {
				/* we got the fs caches */
				if (!sscanf(line, "%*s %lf", &bytesCache)) {
					bytesCache = -1;
				}
			} 
		}

		/* let's check if we got something useful */
		if (bytesFree == -1 || bytesBuffer == -1 || bytesCache == -1) {
			DDEBUG("PassiveMemoryGetFree: unknown /proc/meminfo format\n");
		} else {
			/* let's compute the free memory */
			ret = (bytesFree + bytesBuffer + bytesCache)/1024;
		}
		fclose(file);
	}

	/* if we fail to read /proc we use the NWS standard call (uses
	 * sysconf) */
	if (ret <= 0) {
		ret = AvailableMemory();
	}

	if (ret >= 0) 
		DDEBUG1("getFreeMem: %f MBytes free memory\n", ret);

	return ret;
}

int
PassiveMemoryGetFree(double *measure) {
	double ret;

	ret = getFreeMem();
	if (ret <= 0) {
		return 0;
	}

	*measure = ret;
	LOG1("PassiveMemoryGetFree: %f MBytes free memory\n", ret);

	return 1;
}
	

int
PassiveMemoryMonitorAvailable(void) {
	/* the easy way to test if we can get some data, is to run
	 * getFreeMem and see if we got anything back */
	return (getFreeMem() > 0);
}