1
votes

I'm a noob to linux kernel programming and thought I'd be able to find the answer for this (since it seems really simple) but haven't had any luck yet. I need to make a linux kernel module that prints the version number of the kernel. The assignment requires that implement a module which displays this kind of message when loaded:

"Hello Master. You are currently using Linux (version)", where (version) is the kernel version no.

How can I do this? I tried using uname (http://man7.org/linux/man-pages/man2/uname.2.html) but when I include sys/utsname.h, I get a fatal error upon compiling with my makefile

"Cannot open include file: 'sys/utsname.h': No such file or directory".

Here is my module

#undef __KERNEL__
#define __KERNEL__

#undef __MODULE__
#define __MODULE__

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <sys/utsname.h>

struct utsname unameData;

static int __init config_init(void)
{
    uname(&unameData);
    printk(KERN_INFO "Version number is %s\n", unameData.version);
    return 0;
}

static void __exit config_exit(void)
{
    printk(KERN_INFO "config_exit executed with success\n");
    return;
}

module_init(config_init);
module_exit(config_exit);

MODULE_LICENSE("GPL");

Makefile

obj-m := config.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)

all:
    $(MAKE) -C  $(KDIR) M=$(PWD) modules

clean:
    $(MAKE) -C  $(KDIR) M=$(PWD) clean
1

1 Answers

2
votes

Firstly, you need to use the correct headers and also the correct function utsname(). Following code work well for me.

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/utsname.h>


static int __init my_init(void)
{
        printk(KERN_INFO "Kernel version %s\n", utsname()->version);
        printk(KERN_INFO "Kernel release %s\n", utsname()->release);

        return 0;
}

static void __exit my_exit(void)
{
        printk(KERN_INFO "exit module");

        return;
}

module_init(my_init);
module_exit(my_exit);

MODULE_LICENSE("GPL");

dmesg output should looks something like this:

[ 1117.358451] Kernel version #64-Ubuntu SMP Mon Sep 22 21:28:38 UTC 2014
[ 1117.358457] Kernel release 3.13.0-37-generic