I have seen posts like this on StackOverflow which talk about using uname() to get the current Kernel version number (stored in utsname.release). However that returns a string.
Is there a way to return the or check the Kernel version as a numerical value so that one can simply use if (version >= min_req_ver) { ... } ?
The only method I have seen is to include linux/version.h and check LINUX_VERSION_CODE however in CentOS for example, this version number is not updated when one runs a newer Kernel than the default. The uname() function however does report the correct current Kernel version across Linux distros (on the ones I have tested) including in scenario such as using CentOS with a newer Kernel.
Use below function to get Kernel, Major, Minor and Patch version and compare individual version.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <sys/utsname.h>
int main(void) {
struct utsname buffer;
char *p;
long ver[16];
int i=0;
errno = 0;
if (uname(&buffer) != 0) {
perror("uname");
exit(EXIT_FAILURE);
}
printf("system name = %s\n", buffer.sysname);
printf("node name = %s\n", buffer.nodename);
printf("release = %s\n", buffer.release);
printf("version = %s\n", buffer.version);
printf("machine = %s\n", buffer.machine);
#ifdef _GNU_SOURCE
printf("domain name = %s\n", buffer.domainname);
#endif
p = buffer.release;
while (*p) {
if (isdigit(*p)) {
ver[i] = strtol(p, &p, 10);
i++;
} else {
p++;
}
}
printf("Kernel %d Major %d Minor %d Patch %d\n", ver[0], ver[1], ver[2], ver[3]);
return EXIT_SUCCESS;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With