11
#define MEMINFO_FILE "/proc/meminfo"
12
#define MTAB_FILE "/etc/mtab"
14
#define BAD_OPEN_MESSAGE \
15
"Error: /proc must be mounted\n" \
16
" To mount /proc at boot you need an /etc/fstab line like:\n" \
17
" /proc /proc proc defaults\n" \
18
" In the meantime, run \"mount /proc /proc -t proc\"\n"
20
/* This macro opens filename only if necessary and seeks to 0 so
21
* that successive calls to the functions are more efficient.
22
* It also reads the current contents of the file into the global buf.
24
#define FILE_TO_BUF(filename) do{ \
25
static int fd, local_n; \
26
if ((fd = open(filename, O_RDONLY)) == -1) { \
27
fputs(BAD_OPEN_MESSAGE, stderr); \
31
lseek(fd, 0L, SEEK_SET); \
32
if ((local_n = read(fd, buf, sizeof buf - 1)) < 0) { \
37
buf[local_n] = '\0'; \
42
typedef struct mem_table_struct {
43
const char *name; /* memory type name */
44
unsigned long *slot; /* slot in return struct */
47
static int compare_mem_table_structs(const void *a, const void *b){
48
return strcmp(((const mem_table_struct*)a)->name,((const mem_table_struct*)b)->name);
51
size_t get_free_memory(void){
53
unsigned long kb_main_buffers, kb_main_cached, kb_main_free;
54
char namebuf[16]; /* big enough to hold any row name */
55
mem_table_struct findme = { namebuf, NULL};
56
mem_table_struct *found;
60
const mem_table_struct mem_table[] = {
61
{"Buffers", &kb_main_buffers}, // important
62
{"Cached", &kb_main_cached}, // important
63
{"MemFree", &kb_main_free}, // important
65
const int mem_table_count = sizeof(mem_table)/sizeof(mem_table_struct);
67
FILE_TO_BUF(MEMINFO_FILE);
71
tail = strchr(head, ':');
74
if(strlen(head) >= sizeof(namebuf)){
79
found = bsearch(&findme, mem_table, mem_table_count,
80
sizeof(mem_table_struct), compare_mem_table_structs
83
if(!found) goto nextline;
84
*(found->slot) = strtoul(head,&tail,10);
86
tail = strchr(head, '\n');
91
return (kb_main_buffers + kb_main_cached + kb_main_free) * 1024;
95
int get_file_fs(const char *fname, size_t size, char *fs) {
106
if ((!fname)||(!fs)||(size < 3)) return EINVAL;
111
if (!getcwd(buf, 4095)) return errno;
112
fn = malloc(strlen(fname) + strlen(buf) + 2);
113
if (!fn) return ENOMEM;
114
sprintf(fn, "%s/%s", buf, fname);
117
if (!stat(fn, &st)) {
118
if (S_ISBLK(st.st_mode)) {
124
FILE_TO_BUF(MTAB_FILE);
128
head = strchr(head, ' ');
132
tail = strchr(head, ' ');
138
if((len <= max)||(strncmp(head, fn, len))) {
144
tail = strchr(head, ' ');
149
if (!strncasecmp(head,"root",4)) {
156
if (strlen(head) >= size) err = EFAULT;
164
tail = strchr(head, '\n');
170
if (fn != fname) free(fn);