Skip to content

Instantly share code, notes, and snippets.

@sck
Created August 23, 2012 18:19
Show Gist options
  • Select an option

  • Save sck/3439836 to your computer and use it in GitHub Desktop.

Select an option

Save sck/3439836 to your computer and use it in GitHub Desktop.
Show free memory on OS X
/*
* free.c - show free memory on OS X
* The api query code was extraced from Apple's vm_stat.c
* To compile: gcc -o free free.c
* Output: <byte count> <human readable bytecount>
*/
#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <mach/mach.h>
int humanize_byte_count(char (*r)[1024], double v) {
int i = 0;
char *units = "b KBMBGBTB";
int max_unit = strlen(units) / 2;
while (v > 1024 && i < max_unit) {
v = v / 1024.0;
i++;
}
snprintf((char *)r, 1023, "%0.2f%c%c", v, units[i*2], units[i*2+1]);
return 1;
}
int main(int argc, char *argv[]) {
vm_statistics64_data_t vm_stat;
mach_port_t host;
char *progname = argv[0];
vm_size_t pageSize = 4096;
host = mach_host_self();
if(host_page_size(mach_host_self(), &pageSize) != KERN_SUCCESS) {
fprintf(stderr, "%s: failed to get pagesize; defaulting to 4K.\n",
progname);
pageSize = 4096;
}
unsigned int count = HOST_VM_INFO64_COUNT;
kern_return_t ret;
if ((ret = host_statistics64(host, HOST_VM_INFO64, (host_info64_t)&vm_stat,
&count) != KERN_SUCCESS)) {
fprintf(stderr, "%s: failed to get statistics. error %d\n", progname, ret);
exit(EXIT_FAILURE);
}
uint64_t fm = vm_stat.free_count * pageSize;
char hc[1024];
humanize_byte_count(&hc, fm);
printf("%lld %s\n", fm, hc);
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment