2 * mem_gnu.c - module to get memory/swap usages, for GNU/Hurd
4 * Copyright(C) 2014 Svante Signell <svante.signell@gmail.com>
5 * Copyright(C) 2001,2002 Seiichi SATO <ssato@sh.rim.or.jp>
6 * Copyright(C) 2001 John McCutchan <ttb@tentacle.dhs.org>
8 * licensed under the GPL
19 #if defined(HAVE_STRING_H)
21 #elif defined(HAVE_STRINGS_H)
25 #include <sys/types.h>
29 #include <sys/utsname.h>
33 # define INLINE_STATIC static
35 # define INLINE_STATIC static inline
38 /* initialize function */
42 int version
, patchlevel
;
44 /* get kernel version */
47 sscanf(un
.release
, "%d.%d", &version
, &patchlevel
);
51 INLINE_STATIC
char *skip_line(const char *p
)
58 INLINE_STATIC
char *skip_token(const char *p
)
62 while (*p
&& !isspace(*p
))
67 INLINE_STATIC
char *skip_multiple_token(const char *p
, int count
)
70 for (i
= 0; i
< count
; i
++)
75 /* return mem/swap usage in percent 0 to 100 */
76 void mem_getusage(int *per_mem
, int *per_swap
, const struct mem_options
*opts
)
78 char buffer
[BUFSIZ
], *p
;
80 u_int64_t mtotal
, mused
, mfree
, mbuffer
, mcached
;
81 u_int64_t stotal
, sused
, sfree
, scached
= 0;
83 /* read /proc/meminfo */
84 fd
= open("/proc/meminfo", O_RDONLY
);
86 perror("can't open /proc/meminfo");
89 len
= read(fd
, buffer
, BUFSIZ
- 1);
91 perror("can't read /proc/meminfo");
100 /* examine each line of file */
101 mtotal
= strtoul(p
, &p
, 0); p
= skip_multiple_token(p
, 2);
102 mfree
= strtoul(p
, &p
, 0); p
= skip_multiple_token(p
, 2);
103 mbuffer
= strtoul(p
, &p
, 0); p
= skip_multiple_token(p
, 2);
104 mcached
= strtoul(p
, &p
, 0); p
= skip_multiple_token(p
, 2);
105 scached
= strtoul(p
, &p
, 0);
107 /* skip N lines and examine info about swap */
108 while (isprint(p
[0])) {
110 if (strncmp(p
, "SwapTotal", 9) == 0)
115 stotal
= strtoul(p
, &p
, 0); p
= skip_multiple_token(p
, 2);
116 sfree
= strtoul(p
, &p
, 0);
118 /* calculate memory usage in percent */
119 mused
= mtotal
- mfree
;
120 if (opts
->ignore_buffers
)
122 if (opts
->ignore_cached
)
124 *per_mem
= 100 * (double) mused
/ (double) mtotal
;
126 /* calculate swap usage in percent */
127 sused
= stotal
- sfree
;
128 if (opts
->ignore_cached
)
133 *per_swap
= 100 * (double) sused
/ (double) stotal
;
136 printf("-----------------------\n");
137 printf("MemTotal: %12ld\n", (unsigned long)mtotal
);
138 printf("MemFree: %12ld\n", (unsigned long)mfree
);
139 printf("Buffers: %12ld\n", (unsigned long)mbuffer
);
140 printf("Cached: %12ld\n", (unsigned long)mcached
);
141 printf("SwapTotal: %12ld\n", (unsigned long)stotal
);
142 printf("SwapFree: %12ld\n", (unsigned long)sfree
);
143 printf("SwapCached:%12ld\n", (unsigned long)scached
);
144 printf("-----------------------\n\n");