fdh fdh - 4 months ago 15
Objective-C Question

Retrieve RAM info on a Mac?

I need to retrieve the total amount of RAM present in a system and the total RAM currently being used, so I can calculate a percentage. This is similar to: Retrieve system information on MacOS X?

However, in that question the best answer suggests how to get RAM by reading from:

/usr/bin/vm_stat


Due to the nature of my program, I found out that I am not cannot read from that file - I require a method that will provide me RAM info without simply opening a file and reading from it. I am looking for something to do with function calls. Something like this preferably :
getTotalRam()
and
getRamInUse()
.

I obviously do not expect it to be that simple but I was looking for a solution other than reading from a file.

I am running Mac OS X Snow Leopard, but would preferably get a solution that would work across all current Mac OS X Platforms (i.e. Lion).

Solutions can be in C++, C or Obj-C, however C++ would the best possible solution in my case so if possible please try to provide it in C++.

Answer

You're not supposed to read from /usr/bin/vm_stat, rather you're supposed to run it; it is a program. Look at the first four lines of output

Pages free:                  1880145.
Pages active:                  49962.
Pages inactive:                43609.
Pages wired down:             123353.

Add the numbers in the right column and multiple by the system page size (as returned by getpagesize()) and you get the total amount of physical memory in the system in bytes.

vm_stat isn't setuid on Mac OS, so I assume there is a non-privileged API somewhere to access this information and that vm_stat is using it. But I don't know what that interface is.

Comments