开发者

How can I programmatically check free system memory on Mac like the Activity Monitor does?

On Mac OS X, I can see how much memory is开发者_Python百科 free in Activity Monitor. How can I programmatically do this?


This should do it. Google around for the exact meaning of the fields in the structures, but it should be pretty self-explanatory working from this code.

#import <sys/sysctl.h>
#import <mach/host_info.h>
#import <mach/mach_host.h>
#import <mach/task_info.h>
#import <mach/task.h>
int mib[6]; 
mib[0] = CTL_HW;
mib[1] = HW_PAGESIZE;

int pagesize;
size_t length;
length = sizeof (pagesize);
if (sysctl (mib, 2, &pagesize, &length, NULL, 0) < 0)
{
    fprintf (stderr, "getting page size");
}

mach_msg_type_number_t count = HOST_VM_INFO_COUNT;

vm_statistics_data_t vmstat;
if (host_statistics (mach_host_self (), HOST_VM_INFO, (host_info_t) &vmstat, &count) != KERN_SUCCESS)
{
    fprintf (stderr, "Failed to get VM statistics.");
}

double total = vmstat.wire_count + vmstat.active_count + vmstat.inactive_count + vmstat.free_count;
double wired = vmstat.wire_count / total;
double active = vmstat.active_count / total;
double inactive = vmstat.inactive_count / total;
double free = vmstat.free_count / total;

task_basic_info_64_data_t info;
unsigned size = sizeof (info);
task_info (mach_task_self (), TASK_BASIC_INFO_64, (task_info_t) &info, &size);

double unit = 1024 * 1024;
memLabel.text = [NSString stringWithFormat: @"% 3.1f MB\n% 3.1f MB\n% 3.1f MB", vmstat.free_count * pagesize / unit, (vmstat.free_count + vmstat.inactive_count) * pagesize / unit, info.resident_size / unit];


Actually, that's only half true.

free is not standard UNIX but a Linux-only command. You will neither find it on BSD, nor on OS X.

For that matter, a better way to get memory information is through sysctl.

I.e. run sysctl -a | grep -Ei "(hw|vm)\..*mem"

and you'll get the idea.

To use this programmatically in C, refer to man sysctlbyname.

Also, I don't see how GNOME System Monitor helps on OS X.

df is a good hint, though.

If you just plan to use the shell to gather those data and opt for top, read man top. You can invoke top with -l 1 to get one sample only and limit the process table to, say, 20 processes with -n 20. Keep in mind that you won't get CPU values for procs using only sample, the reason is outlined in the man page.

A simple example to get some information about memory out of top (complete lines only):

top -l1 -n 20 | grep -Ei "mem|vm"

Hope that helps.


The usual commands to do that on UNIX are

  • df -h for hard drive usage
  • free for RAM and swap usage

You would then use/chain one or many of those to extract one of the information given: ack, sed, grep, head, cut, ...

Note: If you don't plan to "programmatically" check memory, I would advise you to rather use top to know which processes are using your CPU and RAM. Gnome System Monitor is one of its GUI equivalents.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜