我只是对宏LINUX_VERSION_CODE犯了一个错误。 这是我想做的,在执行代码时,由于运行的机器,代码会运行不同的分支。
我刚刚意识到,结果不会改变,因为我总是在同一服务器上编译代码。例如,我在2.6.18内核版本中编译belw代码,那么LINUX_VERSION_CODE marco始终为132626。
如果可以的话,由于它运行的版本不同,让它运行另一个分支吗?
#include <stdio.h>
#include <linux/version.h>
int main()
{
printf("kernel version(2.6.32) = %d\n",KERNEL_VERSION(2,6,32));
printf("LINUX_VERSION_CODE = %d\n",LINUX_VERSION_CODE);
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,32)
printf("Hello,world.\n");
#else
printf("Fine,thank you.\n");
#endif
return 0;
}
答案 0 :(得分:1)
因此,您要根据内核版本运行其他代码。但是您不想使用编译时间常数来决定它-您想要在运行时。
没有比这更简单的了,只是调用uname:
#include <sys/utsname.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
struct utsname name;
if (uname(&name)) {
fprintf(stderr, "Uname failed!\n");
exit(-1);
}
printf("%s\n", name.release);
if (!memcmp(&name.release, "4.18.9-", sizeof("4.18.9-") - 1)) {
printf("Och, kernel 4.18.9 found!\n");
} else {
printf("Och, you've got a different kernel...\n");
}
}
在我的机器上:
$ cat 1.c | gcc -xc - && ./a.out
4.18.9-arch1-1-ARCH
Och, kernel 4.18.9 found!
在我的朋友的机器上:
cat 1.c | ssh friend 'gcc -xc - && ./a.out'
4.12.14-lp150.11-default
Och, you've got a different kernel...
我将其留给OP,以调用strtoll或sscanf(&name.release, "%d.%d.%d-", &major, &minor, &release)
来获取内核版本为整数。
但是,您可以获得更多的支持。在运行时,您可以执行任何操作,因此只需读取/usr/include/linux/version.h文件的内容:
#define _GNU_SOURCE 1
#include <linux/version.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *f;
f = fopen("/usr/include/linux/version.h", "r");
if (f == NULL) return -__LINE__;
char *line = NULL;
size_t linelen = 0;
char *found = NULL;
while (getline(&line, &linelen, f) > 0) {
if ((found = strstr(line, "LINUX_VERSION_CODE")) != NULL) {
break;
}
}
if (found == NULL) return -__LINE__;
fclose(f);
found += sizeof("LINUX_VERSION_CODE") - 1;
errno = 0;
const long long kv = strtoll(found, NULL, 10);
if (errno) return -__LINE__;
free(line);
printf("%ld.%ld.%ld\n", kv>>16&0xff, kv>>8&0xff, kv&0xff);
if (kv > KERNEL_VERSION(4,17,0)) {
printf("Och, kernel api greater then 4.17.0 found!\n");
} else {
printf("Och, kernel api below 4.17.0 found!\n");
}
}
在我的机器上,输出:
$ cat 1.c | gcc -xc - && ./a.out
4.17.11
Och, kernel api greater then 4.17.0 found!
还有我的朋友们
$ cat 1.c | ssh friend 'gcc -xc - && ./a.out'
4.15.0
Och, kernel api below 4.17.0 found!
我们还可以看到uname -a
!= grep "LINUX_VERSION_CODE" /usr/include/linux/version.h
。