Determining system memory

Dave Curry davy at ea.ecn.purdue.edu
Fri Apr 1 07:04:57 AEST 1988


In article <248 at lxn.UUCP> chris at lxn.UUCP (Christopher D. Orr) writes:
>
>I have been trying to find a nice, clean way to determine system
>memory under SYS V 2.2.  I have come up with two solutions to this
>problem.  However, there must be a cleaner/faster way :-).
>

Of course the simplest and fastest way, assuming you have the
permissions, is to just go dig it out of the kernel.

--Dave

/*
 * Figure out how much memory there is on a machine.  This works under
 * Berkeley UNIX.  It should work under System V if you change the
 * UNIX define to "/unix" instead of "/vmunix".
 *
 * Of course, if you don't have read permission on the kernel and 
 * kernel memory, this won't work.
 *
 * Dave Curry
 * Purdue University
 * Engineering Computer Network
 * davy at intrepid.ecn.purdue.edu
 */
#include <sys/param.h>
#include <sys/types.h>
#include <nlist.h>
#include <stdio.h>

#ifndef ctob			/* For System V */
#include <sys/sysmacros.h>
#endif

#define UNIX	"/vmunix"
#define KMEM	"/dev/kmem"

struct nlist nl[] = {
#define X_PHYSMEM	0
	{ "_physmem" },
#define X_MAXMEM	1
	{ "_maxmem" },
	{ NULL }
};

main()
{
	int kmem;
	int maxmem, physmem;

	/*
	 * Look up addresses of variables.
	 */
	if ((nlist(UNIX, nl) < 0) || (nl[0].n_type == 0)) {
		fprintf(stderr, "%s: no namelist.\n", UNIX);
		exit(1);
	}

	/*
	 * Open kernel memory.
	 */
	if ((kmem = open(KMEM, 0)) < 0) {
		perror(KMEM);
		exit(1);
	}

	/*
	 * Read variables.
	 */
	lseek(kmem, (long) nl[X_PHYSMEM].n_value, 0);
	read(kmem, (char *) &physmem, sizeof(int));

	lseek(kmem, (long) nl[X_MAXMEM].n_value, 0);
	read(kmem, (char *) &maxmem, sizeof(int));

	close(kmem);

	/*
	 * Print the numbers.  The internal representation is
	 * in units of core clicks; convert to bytes.
	 */
	printf("Physical machine memory: %d\n", ctob(physmem));
	printf("Max memory available to a process: %d\n", ctob(maxmem));

	exit(0);
}



More information about the Comp.unix.questions mailing list