10
#define MEMINFO_FILE "/proc/meminfo"
11
#define MTAB_FILE "/etc/mtab"
13
#define BAD_OPEN_MESSAGE \
14
"Error: /proc must be mounted\n" \
15
" To mount /proc at boot you need an /etc/fstab line like:\n" \
16
" /proc /proc proc defaults\n" \
17
" In the meantime, run \"mount /proc /proc -t proc\"\n"
19
/* This macro opens filename only if necessary and seeks to 0 so
20
* that successive calls to the functions are more efficient.
21
* It also reads the current contents of the file into the global buf.
23
#define FILE_TO_BUF(filename) do{ \
24
static int fd, local_n; \
25
if ((fd = open(filename, O_RDONLY)) == -1) { \
26
fputs(BAD_OPEN_MESSAGE, stderr); \
30
lseek(fd, 0L, SEEK_SET); \
31
if ((local_n = read(fd, buf, sizeof buf - 1)) < 0) { \
36
buf[local_n] = '\0'; \
41
typedef struct mem_table_struct {
42
const char *name; /* memory type name */
43
unsigned long *slot; /* slot in return struct */
46
static int compare_mem_table_structs(const void *a, const void *b){
47
return strcmp(((const mem_table_struct*)a)->name,((const mem_table_struct*)b)->name);
50
size_t get_free_memory(void){
52
unsigned long kb_main_buffers, kb_main_cached, kb_main_free;
53
char namebuf[16]; /* big enough to hold any row name */
54
mem_table_struct findme = { namebuf, NULL};
55
mem_table_struct *found;
59
const mem_table_struct mem_table[] = {
60
{"Buffers", &kb_main_buffers}, // important
61
{"Cached", &kb_main_cached}, // important
62
{"MemFree", &kb_main_free}, // important
64
const int mem_table_count = sizeof(mem_table)/sizeof(mem_table_struct);
66
FILE_TO_BUF(MEMINFO_FILE);
70
tail = strchr(head, ':');
73
if(strlen(head) >= sizeof(namebuf)){
78
found = bsearch(&findme, mem_table, mem_table_count,
79
sizeof(mem_table_struct), compare_mem_table_structs
82
if(!found) goto nextline;
83
*(found->slot) = strtoul(head,&tail,10);
85
tail = strchr(head, '\n');
90
return (kb_main_buffers + kb_main_cached + kb_main_free) * 1024;
94
int get_file_fs(const char *fname, size_t size, char *fs) {
105
if ((!fname)||(!fs)||(size < 3)) return -1;
110
if (!getcwd(buf, 4095)) return -1;
111
fn = malloc(strlen(fname) + strlen(buf) + 2);
113
sprintf(fn, "%s/%s", buf, fname);
116
if (!stat(fn, &st)) {
117
if (S_ISBLK(st.st_mode)) {
123
FILE_TO_BUF(MTAB_FILE);
127
head = strchr(head, ' ');
131
tail = strchr(head, ' ');
137
if((len <= max)||(strncmp(head, fn, len))) {
143
tail = strchr(head, ' ');
148
if (!strncasecmp(head,"root",4)) {
155
if (strlen(head) >= size) err = -1;
163
tail = strchr(head, '\n');
169
if (fn != fname) free(fn);