Mac sysctl and CTL_VM

SamMiller0

macrumors member
Original poster
Aug 17, 2004
65
0
San Jose, CA
I am trying to get the total amount of virtual memory on my system using the following code:

Code:
      //get the swap size
	int vmmib[2] = {CTL_VM,VM_METER};
	struct vmtotal myVirtualMemoryInfo;
	size_t vmlen = sizeof(myVirtualMemoryInfo);
	if (sysctl(vmmib, 2, &myVirtualMemoryInfo, &vmlen, NULL, NULL) == -1) {
		fountainLog(QLOG_ERR, "Could not collect VM info, errno %d - %s", errno, strerror(errno));
		result = FAILURE;
	} else {
		totalSWAP = myVirtualMemoryInfo.t_vm;
		totalSWAP = static_cast<double>(totalSWAP) / 1024.0;
	}
This doesn't work on MacOS 10.3.9, sysctl returns -1 and errno is set to ENOENT meaning: "The name array specifies a value that is unknown". Anyone run into this before?
 

iMeowbot

macrumors G3
Aug 30, 2003
8,634
0
This should get you in the general direction.

Code:
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/sysctl.h>

int
main()
{
    int vmmib[2] = {CTL_VM, VM_SWAPUSAGE};
    struct xsw_usage swapused; /* defined in sysctl.h */
    size_t swlen = sizeof(swapused);
    if (sysctl(vmmib, 2, &swapused, &swlen, NULL, 0) == -1) {
        fprintf(stderr, "Could not collect VM info, errno %d - %s",
                errno, strerror(errno));
        return 1;
    }
    else {
        printf("Total swap: %llu\n", swapused.xsu_total);
        printf("swap available: %llu\n", swapused.xsu_avail);
        printf("swap used: %llu\n", swapused.xsu_used);
        printf("swap page size: %lu\n", swapused.xsu_pagesize);
    }
    return 0;
}
or, du -k /var/vm for a quick check.

(note: that's tested on Tiger, I don't have anything booted to Panther to check there EDIT: and looking now, Panther is missng that. Ugh.)

more edit: http://darwinsource.opendarwin.org/10.3/system_cmds-279/vm_stat.tproj/ shows the usual way of getting VM info out of OS X. It doesn't really tell you what you were looking for in a useful form though.
 
Comment

SamMiller0

macrumors member
Original poster
Aug 17, 2004
65
0
San Jose, CA
iMeowbot said:
(note: that's tested on Tiger, I don't have anything booted to Panther to check there EDIT: and looking now, Panther is missng that. Ugh.)
Thanks, this should work for now. It's ok to require Tiger, but how can I mask the code from being compiled under earlier version of MacOS X? Right now I just use:

#if (defined(__MACH__) && defined(__APPLE__))

to prevent the mac-specific code from being compiled under Linux.
 
Comment

iMeowbot

macrumors G3
Aug 30, 2003
8,634
0
No one else uses that, so I'd probably do:

#include <sys/sysctl.h>
...
#ifdef VM_SWAPUSAGE
...
#endif
 
Comment
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.