Skip to content

Instantly share code, notes, and snippets.

@ztmr
Created January 19, 2014 20:11
Show Gist options
  • Save ztmr/8510363 to your computer and use it in GitHub Desktop.
Save ztmr/8510363 to your computer and use it in GitHub Desktop.
OpenBSD equivalent of `free' Linux command. Shows memory usage.
/*
* $Id: $
*
* Module: free -- description
* Created: 15-SEP-2008 17:56
* Author: tmr
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/param.h>
#include <sys/sysctl.h>
typedef struct {
unsigned pages;
unsigned kbytes;
} MemSizeItem;
typedef struct {
MemSizeItem free;
MemSizeItem used;
MemSizeItem total;
} MemInfo;
unsigned page2kbyte (unsigned pageCnt)
{ return (pageCnt * getpagesize ()) >> 10; }
void getMemInfo (MemInfo * mem) {
/* statistics about the UVM memory *
* management system. */
int mib [] = { CTL_VM, VM_UVMEXP };
const int pagesize = getpagesize ();
struct uvmexp our_uvmexp;
size_t size = sizeof (our_uvmexp);
if (sysctl (mib, 2, &our_uvmexp, &size, NULL, 0) < 0) {
fprintf (stderr, "cannot get memory info!");
return;
}
mem->total.pages = our_uvmexp.npages;
mem->free.pages = our_uvmexp.free +our_uvmexp.inactive;
mem->used.pages = mem->total.pages -mem->free.pages;
mem->total.kbytes = page2kbyte (mem->total.pages);
mem->used.kbytes = page2kbyte (mem->used.pages);
mem->free.kbytes = page2kbyte (mem->free.pages);
}
#define FORMAT(name,item) \
printf ("%8s: %8d pages ~=%8d kBytes\n", \
name, item.pages, item.kbytes);
int main (int argc, char * argv []) {
MemInfo mem;
getMemInfo (&mem);
FORMAT ("Total", mem.total);
FORMAT ("Used", mem.used);
FORMAT ("Free", mem.free);
return (0);
}
// vim: fdm=syntax:fdn=1:tw=74:ts=2:syn=c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment