The primary command to get kernel information is uname. The uname command reports basic information about operating system and hardware kernel. For example “name -p” prints the processor type or “unknown”, if it cannot file one.
The “-r” option returns the kernel release version. To get full configuration for currently used kernel run the followung command: “cat /boot/config-$(uname -r)”.
The full information about current kernel may be gotten with “uname -a”:
# uname -a Linux BAMBOO-209 4.4.0-31-generic #50~14.04.1-Ubuntu SMP Wed Jul 13 01:06:37 UTC 2016 i686 i686 i686 GNU/Linux |
Actually uname reads and parses content of /proc/version file, so the same information may be received by reading this file:
# cat /proc/version Linux version 4.4.0-31-generic (buildd@lgw01-01) (gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3) ) #50~14.04.1-Ubuntu SMP Wed Jul 13 01:06:37 UTC 2016 |
The alternative way to get the same information using sysctl (system control) command:
# sysctl kernel.ostype kernel.ostype = Linux # sysctl kernel.osrelease kernel.osrelease = 4.4.0-31-generic # sysctl kernel.version #50~14.04.1-Ubuntu SMP Wed Jul 13 01:06:37 UTC 2016 |
Now how to get the same kernel data programmatically, through . So sysctl API, file kernctl.cpp:
#include <stdio.h>
#include <sys/types.h>
#include <sys/sysctl.h>
int main(int n, char ** s)
{
char szBuffer[255];
size_t length = sizeof(szBuffer);
int mib[4] = {0,0,0,0};
size_t miblen = sizeof(mib)/sizeof(int);
mib[0] = CTL_KERN;
mib[1] = KERN_OSTYPE;
int iError = sysctl(mib, 2, &szBuffer, &length, NULL, 0);
if(iError == 0)
{
printf("OS type: %s\n", szBuffer);
} else {
printf("Cannot get OS type. Error: %d\n", iError);
}
mib[1] = KERN_OSRELEASE;
length = sizeof(szBuffer);
iError = sysctl(mib, 2, &szBuffer, &length, NULL, 0);
if(iError == 0)
{
printf("OS release: %s\n", szBuffer);
} else {
printf("Cannot get OS release. Error: %d\n", iError);
}
mib[1] = KERN_VERSION;
length = sizeof(szBuffer);
iError = sysctl(mib, 2, &szBuffer, &length, NULL, 0);
if(iError == 0)
{
printf("OS version and compile time: %s\n", szBuffer);
} else {
printf("Cannot get OS version. Error: %d\n", iError);
}
return 0;
}
Code testing result:
# g++ -o kernctl.cpp kernctl # ./kernctl OS type: Linux OS release: 4.4.0-31-generic OS version and compile time: #50~14.04.1-Ubuntu SMP Wed Jul 13 01:06:37 UTC 2016 |
The sysctl command and API is specifically designed for kernel parameter tuning and may be used to only for reading kernel data and also for changing them.
Great post.|