sysctl is a operating system command of some Unix-like OS that permits to reads and/or modify the parameters of the OS kernel for example limit and setting values of some system attributes. It is available both as a system API for compiled programs, and an administrator command for terminal interface and scripting. Below presented 2 examples how to use sysctl in C++ code with verification command.
The both samples were related to Mac OSX OS, however for Linux the implementation will be similar ones, the only MIB names may be different.
The first example shows how to get memory size installed on the device:
#include <stdio.h>
#include <sys/sysctl.h>
int main(int n, char ** s)
{
long long memSize;
size_t length = sizeof(long long);
int mib[4] = {0,0,0,0};
size_t miblen = sizeof(mib)/sizeof(int);
sysctlnametomib("hw.memsize", mib, &miblen);
int iError = sysctl(mib, 2, &memSize, &length, NULL, 0);
if(iError == 0)
{
printf("Memory size %lld byte\n", memSize);
} else {
printf("Cannot get memory size. Error: %d\n", iError);
}
return 0;
}
The second one is used to get Mac OSX version, this MIB “kern.osproductversion” is valid only for High Sierra and above:
#include <stdio.h>
#include <string.h>
#include <sys/sysctl.h>
int main(int n, char ** s)
{
char version[32];
memset(version,0,32);
size_t length = sizeof(long long);
int mib[4] = {0,0,0,0};
size_t miblen = sizeof(version);
sysctlnametomib("kern.osproductversion", mib, &miblen);
int iError = sysctl(mib, 2, version, &length, NULL, 0);
if(iError == 0)
{
printf("OS version %s\n", version);
} else {
printf("Cannot OS version. Error: %d\n", iError);
}
return 0;
}
Testing the code:
# ./memsize Memory size 17179869184 bytes # sysctl hw.memsize hw.memsize: 17179869184 # ./osver OS version 10.13.4 # sysctl kern.osproductversion kern.osproductversion: 10.13.4 |