Actually, I didn't expect it.
The reason I didn't expect that to kill "top" and "ps" is that it never
killed "free", which obviously uses /proc/meminfo even more than top and
ps do.
And the reason it didn't kill "free" is that free did it the right way,
reading a line at a time. Instead of looking at the file as some
sequence of characters, /proc/meminfo is built up from _lines_, so the
better way to parse it is simply something like
fgets(f, header, MAXLINE);
fgets(f, mem, MAXLINE);
fgets(f, swap, MAXLINE);
sscanf(mem, "%s %ld %ld ...
or if you feel that fgets and scanf is too slow (which they can be), you
can always do something like this instead
int read_meminfo(void)
{
#define MAXMEM 1000
char buffer[MAXMEM], *mem, *swap;
int fd;
fd = open("/proc/meminfo", O_RDONLY);
if (fd < 0)
return fd;
read(fd, buffer, MAXMEM);
buffer[MAXMEM-1] = 0;
/* get rid of header line */
mem = strchr(buffer, '\n');
if (!mem)
return -1;
*(mem++) = 0;
swap = strchr(mem, '\n');
if (!swap)
return -1;
*(swap++) = 0;
/* get rid of "Mem:" */
mem = strchr(mem, ' ');
if (!mem)
return -1;
total = strtoul(mem, &mem, 0);
used = strtoul(mem, &mem, 0);
free = strtoul(mem, &mem, 0);
shared = strtoul(mem, &mem, 0);
buffers = strtoul(mem, &mem, 0);
cached = strtoul(mem, &mem, 0);
/* get rid of "Swap:" */
swap = strchr(swap, ' ');
if (!mem)
return -1;
total_swap = strtoul(swap, &swap, 0);
used_swap = strtoul(swap, &swap, 0);
free_swap = strtoul(swap, &swap, 0);
return 0;
}
Note that the above is completely untested, and I haven't even tried to
compile it. It's just the general idea: with something like this it
doesn't _matter_ if the format of the file changes a bit or I add new
fields to it. In fact, the above probably works fine for the old format
too ("cached" gets a some random value, but on the whole it should still
work).
The whole idea with ascii free-style strings in the /proc files is that
it allows a program to work even without the traditional fixed-size
binary structure mess. But it _does_ mean that to take full advantage
of this, the program that reads it shouldn't have too fixed an idea
about the actual format of the file. The less fixed formats, the
better, in fact.
Linus